﻿
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using AutoUpdaterDotNET;
using Newtonsoft.Json;
using QQTools.Core;
using QQTools.Core.Enums.ForwardGroupMessage;
using QQTools.Data;
using QQTools.Data.Enums.AddGroup;
using QQTools.Data.Enums.BlockGroup;
using QQTools.Data.Enums.InviteGroup;
using QQTools.Data.Models;
using QQTools.Data.Plus;
using QQTools.Data.Repositories;
using QQTools.Data.Repositories.AddGroup;
using QQTools.Data.Repositories.BlockGroup;
using QQTools.Data.Repositories.InviteGroup;
using QQTools.Data.Repositories.ForwardGroupMessage;
using QQTools.Logging;
using QQTools.Services;

using QQTools.Services.Tasks;
using QQTools.Utils;
using QQTools.Core.Enums.SendGroupMessage;
using QQTools.Data.Models.SendGroupMsg;
using QQTools.Data.Repositories.SendGroupMessage;
using QQTools.Services.Automation;
using System.Security.Cryptography;



namespace QQTools
{
    public partial class MainForm : Form
    {

        /// <summary>
        /// 程序配置文件路径
        /// </summary>
        private readonly string jsonFilePath = "C:\\QQ怀旧助手配置\\controls_data.json";

        private readonly QQService _qqService;
        private readonly QQRepository _qqRepository;

        /// <summary>
        /// 加群任务
        /// </summary>
        private readonly AddGroupRepository _addGroupRepository;
        private readonly AddGroupQQRepository _addGroupQQRepository;
        private readonly AddGroupServices _addGroupServices;


        /// <summary>
        /// 邀请加群
        /// </summary>
        private readonly InviteGroupQQRepository _inviteGroupQQRepository;
        private readonly InviteGroupRepository _inviteGroupRepository;
        private readonly InviteGroupServices _inviteGroupServices;


        /// <summary>
        /// 屏蔽群聊
        /// </summary>
        private readonly BlockGroupQQRepository _blockGroupQQRepository;
        private readonly BlockGroupRepository _blockGroupRepository;
        private readonly BlockGroupServices _blockGroupServices;


        /// <summary>
        /// 转发消息
        /// </summary>
        private readonly ForwardGroupMsgQQRepository _forwardGroupMsgQQRepository;
        private readonly ForwardGroupMsgRepository _forwardGroupMsgRepository;
        private readonly ForwardGroupMsgServices _forwardGroupMsgServices;

        /// <summary>
        /// 群发消息
        /// </summary>
        private readonly SendGroupMsgQQRepository _sendGroupMsgQQRepository;
        private readonly SendGroupMsgRepository _sendGroupMsgRepository;
        private readonly SendGroupMsgServices _sendGroupMsgServices;

        /// <summary>
        /// 设置版本号
        /// </summary>
        private Version _version;

        // 使用 CancellationToken 来取消正在进行的邀请加群任务
        private CancellationTokenSource _inviteGroupTaskCancellationTokenSource;
        // 使用 CancellationToken 来取消正在进行的加群任务
        private CancellationTokenSource _addGroupTaskCancellationTokenSource;
        // 使用 CancellationToken 来取消正在进行的屏蔽群任务
        private CancellationTokenSource _blockGroupTaskCancellationTokenSource;
        // 使用 CancellationToken 来取消正在进行的转发任务
        private CancellationTokenSource _forwardGroupMsgTaskCancellationTokenSource;
        // 使用 CancellationToken 来取消正在进行的群发任务
        private CancellationTokenSource _sendGroupMsgTaskCancellationTokenSource;

        /// <summary>
        /// QQ列表(包含各种信息:群列表,cookie等等)
        /// </summary>
        List<QQModel> QQList;
        public MainForm()
        {
            InitializeComponent();
            // 判断 C:\\QQ怀旧助手配置\\ 目录是否存在
            if (!Directory.Exists("C:\\QQ怀旧助手配置"))
            {
                // 创建 C:\\QQ怀旧助手配置 目录
                Directory.CreateDirectory("C:\\QQ怀旧助手配置");
            }

            // 初始化数据库
            DatabaseContext.InitializeDatabase();
            // 初始化 Repository
            string connectionString = DatabaseContext.ConnectionString;
            // 创建 QQRepository
            _qqRepository = new QQRepository(connectionString);
            _qqService = new QQService(_qqRepository, this);

            // 初始化加群任务 Repository
            _addGroupQQRepository = new AddGroupQQRepository(connectionString);
            _addGroupRepository = new AddGroupRepository(connectionString);
            _addGroupServices = new AddGroupServices(this, _addGroupRepository, _addGroupQQRepository, _qqRepository);

            // 初始化邀请加群 Repository
            _inviteGroupQQRepository = new InviteGroupQQRepository(connectionString);
            _inviteGroupRepository = new InviteGroupRepository(connectionString);
            _inviteGroupServices = new InviteGroupServices(this, _inviteGroupRepository, _inviteGroupQQRepository);

            // 初始化屏蔽群聊 Repository
            _blockGroupQQRepository = new BlockGroupQQRepository(connectionString);
            _blockGroupRepository = new BlockGroupRepository(connectionString);
            _blockGroupServices = new BlockGroupServices(this, _blockGroupRepository, _blockGroupQQRepository);

            // 初始化转发消息 Repository
            _forwardGroupMsgQQRepository = new ForwardGroupMsgQQRepository(connectionString);
            _forwardGroupMsgRepository = new ForwardGroupMsgRepository(connectionString);
            _forwardGroupMsgServices = new ForwardGroupMsgServices(_forwardGroupMsgQQRepository, _forwardGroupMsgRepository, this);

            // 初始化群发消息 Repository
            _sendGroupMsgQQRepository = new SendGroupMsgQQRepository(connectionString);
            _sendGroupMsgRepository = new SendGroupMsgRepository(connectionString);
            _sendGroupMsgServices = new SendGroupMsgServices(_sendGroupMsgQQRepository, _sendGroupMsgRepository, this);

            // 开启双缓冲, 解决ListView闪烁的问题
            /// 新添加这一句调用就行了，如果有ListViews也是这样添加，
            /// 但要注意方法里改为有关ListViews的声明即可
            //listViewBlockGroup.DoubleBufferedListView(true);
            //listViewForwardGroupMsg.DoubleBufferedListView(true);



        }
        #region UI事件
        private async void MainForm_Load(object sender, EventArgs e)
        {

            // 将主窗口移动到屏幕左下角
            this.StartPosition = FormStartPosition.Manual;
            int x = 0;
            int y = Screen.PrimaryScreen.WorkingArea.Height - this.Height;
            this.Location = new Point(x, y);
            _version = new Version("1.0.0.11");
            LogManager.Info($"当前版本:{_version}");

            // 加载QQ信息
            QQList = await _qqService.GetQQList();


            // 如果日期大于2023-01-01,则不加载配置文件
            //if (DateTime.Now > new DateTime(2025, 4, 12))
            //{
            //    MessageBox.Show("当前版本已过期,请重新下载最新版本!");
            //    // 结束程序
            //    Environment.Exit(0);
            //    return;
            //}

            toolStripStatusVersion.Text = $"{_version} ";

            //comboBoxForwardType.SelectedIndex = 1;
            // 默认显示选项卡1
            //tabControl1.SelectedIndex = 1;


            var config = NLog.LogManager.Configuration;
            if (config == null)
            {
                throw new Exception("NLog configuration not loaded.");
            }
            await LoadListViewQQ();
            // 加载所有TextBox的内容
            LoadControlsContents();

            // 初始化选项卡中的数据
            InitTabControl();



        }


        /// <summary>
        /// 初始化选项卡
        /// </summary>
        private async void InitTabControl()
        {
            if (QQList == null)
            {
                LogManager.Info("QQList 尚未加载完成，跳过选项卡处理。");
                return;
            }

            if (tabControl1.SelectedIndex == 0)
            { // 说明选项卡为加群界面
                //// 1.加载邀请任务:QQ列表
                UpdateListViewAddGroupQQ();
                //// 1重置加群任务:群列表 任务状态为进行中的变成待处理
                await _addGroupRepository.ResetStatusToPendingAsync();
                //// 2.加载加群任务:群列表
                UpdateListViewAddGroup();
            }
            else if (tabControl1.SelectedIndex == 1)
            { // 说明选项卡为邀请界面
                //// 1.加载邀请任务:QQ列表
                UpdateListViewInviteGroupQQ();
                //// 2.1重置邀请任务:群列表 任务状态为进行中的变成待处理
                await _inviteGroupRepository.ResetStatusToPendingAsync();
                //// 2.2加载邀请任务:群列表
                UpdateListViewInviteGroup();

            }
            else if (tabControl1.SelectedIndex == 2)
            {// 说明选项卡为屏蔽界面
                //// 1.加载屏蔽任务:QQ列表
                UpdateListViewBlockGroupQQ();
                //// 2.1重置屏蔽任务:群列表 任务状态为进行中的变成待处理
                await _blockGroupRepository.ResetStatusToPendingAsync();
                //// 2.2加载邀请任务:群列表
                UpdateListViewBlockGroup();
            }
            else if (tabControl1.SelectedIndex == 3) // 说明选项卡为转发界面
            {
                // 1.加载转发任务:QQ列表
                UpdateListViewForwardGroupMsgQQ();
                // 2.1重置转发任务:群列表 任务状态为进行中的变成待处理
                await _sendGroupMsgRepository.ResetStatusRunningToNotStartedAsync();
                // 2.2加载转发任务:群列表
                UpdateListViewForwardGroupMsg();
            }
            else if (tabControl1.SelectedIndex == 4) // 说明选项卡为群发界面
            {
                // 1.加载群发任务:QQ列表
                UpdateListViewSendGroupMsgQQ();
                // 2.1重置群发任务:群列表 任务状态为进行中的变成待处理
                await _sendGroupMsgRepository.ResetStatusRunningToNotStartedAsync();
                // 2.2加载群发任务:群列表
                UpdateListViewSendGroupMsg();
            }
        }


        private async Task LoadListViewQQ()
        {
            await Task.Run(async () =>
            {
                // 加载QQ列表
                //if (QQList.Count <= 0)
                //{
                //    QQList = await _qqService.GetQQList();
                //}

                QQList = await _qqService.GetQQList();
                // 自动识别线程, 更新UI
                listViewQQ.InvokeIfRequired(() =>
                {
                    // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                    listViewQQ.BeginUpdate(); // 开始更新
                    listViewQQ.SuspendLayout(); // 禁用布局更新
                    listViewQQ.Items.Clear();
                    foreach (var qq in QQList)
                    {
                        var item = new ListViewItem(new[] {
                            (listViewQQ.Items.Count+1).ToString(),
                            qq.QQ,
                            qq.Nickname,
                            qq.GroupNumber.ToString(),
                            qq.LastHandle.ToString(),
                        });
                        // 将PID 存到 Tag
                        item.Tag = qq.LastPid;
                        listViewQQ.Items.Add(item);
                    }
                    listViewQQ.ResumeLayout(); // 启用布局更新
                    listViewQQ.EndUpdate(); // 结束更新
                });

            });
        }


        private void MainForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            // 保存所有TextBox的内容
            SaveControlsContents();

            // 关闭所有任务
            // 使用 CancellationToken 来取消正在进行的加群任务
            CancelTask(_addGroupTaskCancellationTokenSource);
            // 使用 CancellationToken 来取消正在进行的加群任务
            CancelTask(_inviteGroupTaskCancellationTokenSource);
            // 使用 CancellationToken 来取消正在进行的屏蔽群任务
            CancelTask(_blockGroupTaskCancellationTokenSource);
            // 使用 CancellationToken 来取消正在进行的转发任务
            CancelTask(_forwardGroupMsgTaskCancellationTokenSource);
        }

        /// <summary>
        /// 取消任务
        /// </summary>
        /// <param name="cancellationTokenSource"></param>
        private void CancelTask(CancellationTokenSource cancellationTokenSource)
        {
            if (cancellationTokenSource == null) return;
            if (cancellationTokenSource.IsCancellationRequested == false)
            {
                cancellationTokenSource?.Cancel();
                cancellationTokenSource?.Dispose();
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            // 输入
            // 模拟群发消息
            SendGroupMsgAuto sendGroupMsgAuto = new SendGroupMsgAuto(12404);
            sendGroupMsgAuto.Test();

        }



        #endregion
        /// =====================================================转发Start============================================================
        #region 转发功能模块
        /// <summary>
        /// 更新转发任务QQ列表
        /// </summary>
        /// <param name="forwardGroupMsgQQModel"></param>
        public async void UpdateListViewForwardGroupMsgQQ(ForwardGroupMsgQQModel forwardGroupMsgQQModel = null, string qq = null)
        {
            List<ForwardGroupMsgQQModel> forwardGroupMsgQQModels = new List<ForwardGroupMsgQQModel>();
            try
            {
                if (forwardGroupMsgQQModel == null)
                {
                    // 从数据库加载转发任务
                    forwardGroupMsgQQModels = await _forwardGroupMsgQQRepository.GetAllAsync();
                    if (forwardGroupMsgQQModels.Count() <= 0)
                    {
                        return;
                    }
                }
                else
                {
                    forwardGroupMsgQQModels.Add(forwardGroupMsgQQModel);
                }
                if (qq == null)
                {
                    // 默认第一个QQ为进行时
                    qq = forwardGroupMsgQQModels.FirstOrDefault()?.QQ;
                }
                UpdateListViewForwardGroupMsgQQ(forwardGroupMsgQQModels, qq);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewForwardGroupMsgQQ] UI:更新转发任务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新转发任务QQ列表
        /// </summary>
        /// <param name="forwardGroupMsgQQModels"></param>
        /// <param name="qq"></param>
        public void UpdateListViewForwardGroupMsgQQ(List<ForwardGroupMsgQQModel> forwardGroupMsgQQModels, string qq = null)
        {

            // 自动识别线程, 更新UI
            listViewForwardGroupMsgQQ.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewForwardGroupMsgQQ.BeginUpdate();
                listViewForwardGroupMsgQQ.SuspendLayout(); // 禁用布局更新
                listViewForwardGroupMsgQQ.Items.Clear();

                // 批量添加项
                var itemsToAdd = forwardGroupMsgQQModels.Select((forwardGroupMsgQQ, index) => CreateListViewForwardGroupMsgQQItem(forwardGroupMsgQQ, index + 1, qq)).ToList();
                listViewForwardGroupMsgQQ.Items.AddRange(itemsToAdd.ToArray());

                listViewForwardGroupMsgQQ.ResumeLayout(); // 启用布局更新
                listViewForwardGroupMsgQQ.EndUpdate();
            });
        }

        /// <summary>
        /// 创建一个ForwardGroupMsgQQ Item
        /// </summary>
        /// <param name="forwardGroupMsgQQ"></param>
        /// <param name="index"></param>
        /// <param name="qq">如果qq不为空则设置为正在进行的状态</param>
        /// <returns></returns>
        private ListViewItem CreateListViewForwardGroupMsgQQItem(ForwardGroupMsgQQModel forwardGroupMsgQQ, int index, string qq = null)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(forwardGroupMsgQQ.QQ);
            newItem.SubItems.Add(forwardGroupMsgQQ.ForwardCount.ToString());
            newItem.SubItems.Add(forwardGroupMsgQQ.FailedCount.ToString());


            if (qq != null && string.Equals(forwardGroupMsgQQ.QQ, qq))
            {
                newItem.BackColor = Color.LightSalmon; // 统一颜色设置
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }

            return newItem;
        }


        /// <summary>
        /// 更新转发任务群列表
        /// </summary>
        /// <param name="qq"></param>
        public async void UpdateListViewForwardGroupMsg(string qq)
        {
            if (string.IsNullOrEmpty(qq))
            {
                LogManager.Error($"[UpdateListViewForwardGroupMsg] UI:更新转发任务失败: qq为空");
                return;
            }
            try
            {
                // 获取该QQ的群列表
                List<ForwardGroupMsgModel> forwardGroupMsgModels = await _forwardGroupMsgRepository.GetByQQAsync(qq);
                if (forwardGroupMsgModels == null || forwardGroupMsgModels.Count() <= 0)
                {
                    // 数据库没有该QQ的群列表, 重新获取
                    UpdateListViewForwardGroupMsg(qq, null);
                }
                else
                {
                    // 默认该QQ的第一个群号为进行时
                    UpdateListViewForwardGroupMsg(forwardGroupMsgModels, forwardGroupMsgModels.FirstOrDefault()?.GroupNumber);
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewForwardGroupMsg] UI:更新转发任务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新转发任务群列表
        /// </summary>
        /// <param name="forwardGroupMsgQQModel"></param>
        public async void UpdateListViewForwardGroupMsg(ForwardGroupMsgModel forwardGroupMsgModel)
        {
            if (forwardGroupMsgModel == null)
            {
                LogManager.Error($"[UpdateListViewForwardGroupMsg] UI:更新转发任务失败: forwardGroupMsgModel为空");
                return;
            }

            try
            {
                List<ForwardGroupMsgModel> forwardGroupMsgModels = await _forwardGroupMsgRepository.GetByQQAsync(forwardGroupMsgModel.QQ);
                if (forwardGroupMsgModels == null || forwardGroupMsgModels.Count() <= 0)
                {
                    LogManager.Error($"[UpdateListViewForwardGroupMsg] UI:更新转发任务失败: qq:{forwardGroupMsgModel.QQ}的群为空");
                    return;
                }
                UpdateListViewForwardGroupMsg(forwardGroupMsgModels, forwardGroupMsgModel.GroupNumber);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewForwardGroupMsg] UI:更新转发任务失败: {ex.Message}");
            }
        }


        /// <summary>
        /// 更新转发任务群列表
        /// </summary>
        /// <param name="qq"></param>
        /// <param name="groupNumber"></param>
        public async void UpdateListViewForwardGroupMsg(string qq = null, string groupNumber = null)
        {
            // 获取对应QQ的群列表
            // QQList = _qqService.GetQQList();
            List<ForwardGroupMsgModel> forwardGroupMsgModels = new List<ForwardGroupMsgModel>();

            // 获取所有转发任务QQ
            List<ForwardGroupMsgQQModel> forwardGroupMsgQQModels = await _forwardGroupMsgQQRepository.GetAllAsync();
            if (forwardGroupMsgQQModels.Count() <= 0)
            {
                LogManager.Info($"[UpdateListViewForwardGroupMsg] 暂无转发任务!");
                return;
            }
            // 默认发送图片
            ForwardGroupMsgType msgType = ForwardGroupMsgType.图片;
            // 获取当前发送的资源类型
            comboBoxForwardType.InvokeIfRequired(() =>
            {
                if (comboBoxForwardType.SelectedIndex == -1)
                {
                    msgType = ForwardGroupMsgType.图片;
                }
                else
                {
                    msgType = (ForwardGroupMsgType)comboBoxForwardType.SelectedIndex;
                }
            });


            List<ForwardGroupMsgModel> fristQQGroupList = new List<ForwardGroupMsgModel>();

            foreach (var forwardGroupMsgQQModel in forwardGroupMsgQQModels)
            {

                // 从QQList获取qq对应的 QQ的群列表
                var item = QQList.FirstOrDefault(x => x.QQ == forwardGroupMsgQQModel.QQ);
                if (item == null)
                {
                    LogManager.Error($"[UpdateListViewForwardGroupMsg] UI:更新转发任务失败: qq:{forwardGroupMsgQQModel.QQ}的群为空");
                    continue;
                }
                // 组装QQ群列表
                List<ForwardGroupMsgModel> currentQQGroupList = new List<ForwardGroupMsgModel>();
                foreach (var group in item.GroupList)
                {
                    ForwardGroupMsgModel forwardGroupMsgModel = new ForwardGroupMsgModel
                    {
                        QQ = item.QQ,
                        GroupNumber = group,
                        MessageContent = "1",                   // 发送图片的下标
                        MessageType = msgType,
                        Status = ForwardGroupMsgStatus.NotStarted, // 默认:未开始
                        ForwardTime = DateTime.Now,
                        RetryCount = 3,                         // 默认重试3次
                        ForwardCount = 0,                          // 默认发送次数0
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };
                    currentQQGroupList.Add(forwardGroupMsgModel);
                    forwardGroupMsgModels.Add(forwardGroupMsgModel);
                }
            }

            // 批量插入 将群列表存储到数据库
            await _forwardGroupMsgRepository.BulkInsertAsync(forwardGroupMsgModels);


            if (string.IsNullOrEmpty(qq))
            {
                // 如果qq为空,则取出任务列表第一个QQ
                qq = forwardGroupMsgQQModels.FirstOrDefault()?.QQ;
            }

            // 从数据库读取当前QQ的群列表
            List<ForwardGroupMsgModel> forwardGroupMsgModels1 = await _forwardGroupMsgRepository.GetByQQAsync(qq);
            if (forwardGroupMsgModels1 == null)
            {
                LogManager.Error($"[UpdateListViewForwardGroupMsg]  qq:{qq} 从数据库读取当前QQ的群列表失败");
                return;
            }

            if (groupNumber == null)
            {
                // 取出 forward
                // GroupMsgModels1 的第一个元素作为groupNumber
                groupNumber = forwardGroupMsgModels1.FirstOrDefault().GroupNumber;
            }
            // 更新UI;将当前QQ的群列表展示出来
            UpdateListViewForwardGroupMsg(forwardGroupMsgModels1, groupNumber);

        }


        /// <summary>
        /// 更新转发任务群列表
        /// </summary>
        /// <param name="forwardGroupMsgModels"></param>
        /// <param name="groupNumber"></param>
        public void UpdateListViewForwardGroupMsg(List<ForwardGroupMsgModel> forwardGroupMsgModels, string groupNumber = null)
        {

            // 自动识别线程, 更新UI
            listViewForwardGroupMsg.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewForwardGroupMsg.BeginUpdate();
                listViewForwardGroupMsg.SuspendLayout(); // 禁用布局更新
                listViewForwardGroupMsg.Items.Clear();

                if (string.IsNullOrEmpty(groupNumber))
                {
                    // 默认 获取 listViewForwardGroupMsg 第一个的群
                    groupNumber = forwardGroupMsgModels.FirstOrDefault().GroupNumber;
                }

                // 批量添加项
                var itemsToAdd = forwardGroupMsgModels.Select((forwardGroupMsg, index) => CreateListViewForwardGroupMsgItem(forwardGroupMsg, index + 1, groupNumber)).ToList();
                listViewForwardGroupMsg.Items.AddRange(itemsToAdd.ToArray());


                // 将列表滚动到 newItem.BackColor = Color.LightSalmon;
                var targetItem = listViewForwardGroupMsg.Items.Cast<ListViewItem>()
                    .FirstOrDefault(x => x.SubItems[1].Text == groupNumber);

                if (targetItem != null)
                {
                    // 直接定位到目标项的下一个项（如果存在）
                    int itemIndex = listViewForwardGroupMsg.Items.IndexOf(targetItem);
                    // 滚动到将item的下一个的item
                    if (itemIndex < listViewForwardGroupMsg.Items.Count - 1)
                    {
                        listViewForwardGroupMsg.Items[itemIndex + 1].EnsureVisible();
                    }
                    else
                    {
                        // 如果是最后一项，直接滚动到自身
                        targetItem.EnsureVisible();
                    }
                }

                listViewForwardGroupMsg.ResumeLayout(); // 启用布局更新
                listViewForwardGroupMsg.EndUpdate();


            });
        }

        /// <summary>
        /// 创建一个 ForwardGroupMsg Item
        /// </summary>
        /// <param name="forwardGroupMsg"></param>
        /// <param name="index"></param>
        /// <param name="groupNumber">如果groupNumber不为空则设置为正在进行的状态</param>
        /// <returns></returns>
        private ListViewItem CreateListViewForwardGroupMsgItem(ForwardGroupMsgModel forwardGroupMsg, int index, string groupNumber = null)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(forwardGroupMsg.GroupNumber);
            newItem.SubItems.Add(forwardGroupMsg.MessageType.ToString());
            newItem.SubItems.Add($"{forwardGroupMsg.ForwardCount}/{forwardGroupMsg.RetryCount}");
            newItem.SubItems.Add(forwardGroupMsg.Status.ToChineseString());

            //if (groupNumber != null && string.Equals(forwardGroupMsg.GroupNumber, groupNumber))
            //{
            //    newItem.BackColor = Color.LightSalmon; // 统一颜色设置
            //    newItem.EnsureVisible();// 使滚动条自动滚动到该行‌
            //}
            //else
            //{
            //    newItem.BackColor = Color.Transparent;
            //}
            if (forwardGroupMsg.Status == ForwardGroupMsgStatus.Success)
            {
                newItem.BackColor = Color.LightGreen;
            }
            else if (forwardGroupMsg.Status == ForwardGroupMsgStatus.Running || string.Equals(forwardGroupMsg.GroupNumber, groupNumber))
            {
                newItem.BackColor = Color.LightSalmon;
            }
            else if (forwardGroupMsg.Status == ForwardGroupMsgStatus.Failed)
            {
                newItem.BackColor = Color.LightCoral;
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }


            return newItem;
        }


        private async void btnAddForwardGroupMsgTask_Click(object sender, EventArgs e)
        {
            // 刷新添加QQ列表
            // 处理 addGroupsQQ 列表
            // 判断 listViewQQ 的选中相
            // 获取所有勾选的 ListViewItem
            List<ListViewItem> checkedItems = new List<ListViewItem>();
            foreach (ListViewItem item in listViewQQ.Items)
            {
                if (item.Checked)
                { // 检查是否被勾选
                    checkedItems.Add(item);
                }
            }

            if (checkedItems.Count <= 0)
            {
                MessageBox.Show("请先勾选最左侧QQ列表");
                return;
            }
            // 判断邀请功能中的QQ列表是否为空
            List<ForwardGroupMsgQQModel> forwardGroupMsgQQModels = await _forwardGroupMsgQQRepository.GetAllAsync();
            if (forwardGroupMsgQQModels.Count() > 0)
            {
                var result = MessageBox.Show("已有转发任务，删除后无法恢复\n\n\t是否确定删除？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    // UI:删除转发任务:QQ列表
                    listViewForwardGroupMsgQQ.Items.Clear();
                    // 数据库:清空转发任务:forward_group_msg_qq
                    await _forwardGroupMsgQQRepository.ClearTableAsync();


                    // UI:删除转发任务:群列表
                    listViewForwardGroupMsg.Items.Clear();
                    // 数据库:清空转发任务:forward_group_msg
                    await _sendGroupMsgRepository.ClearTableAsync();

                    // 删除记录qq
                    // SaveAddGroudProgress("");

                    LogManager.Info($"[添转发发任务] 清空转发任务:forward_group_msg_qq和forward_group_msg的数据库, 开始新的任务");
                }
                else
                {
                    return;
                }
            }

            await Task.Run(async () =>
            {
                string firstQQ = null;
                forwardGroupMsgQQModels = new List<ForwardGroupMsgQQModel>();
                for (int i = 0; i < checkedItems.Count; i++)
                {
                    ListViewItem item = checkedItems[i];

                    string qq = item.SubItems[1].Text;

                    // 插入到 forward_group_msg_qq 表中
                    ForwardGroupMsgQQModel forwardGroupMsgQQModel = new ForwardGroupMsgQQModel();

                    forwardGroupMsgQQModel.QQ = qq;
                    forwardGroupMsgQQModel.ForwardCount = 0;
                    forwardGroupMsgQQModel.FailedCount = 0;
                    forwardGroupMsgQQModel.ResourceIndex = 1; // 默认资源下标为1
                    forwardGroupMsgQQModel.CreateTime = DateTime.Now;
                    forwardGroupMsgQQModel.UpdateTime = DateTime.Now;

                    await _forwardGroupMsgQQRepository.AddOrUpdateAsync(forwardGroupMsgQQModel);
                    if (i == 0)
                    {
                        // 将第一个QQ设置为正在进行的状态
                        firstQQ = qq;
                    }
                    forwardGroupMsgQQModels.Add(forwardGroupMsgQQModel);
                }
                // 更新UI:ListViewForwardGroupMsgQQ, 将第一个QQ设置为正在进行的状态
                UpdateListViewForwardGroupMsgQQ(forwardGroupMsgQQModels, firstQQ);
                // 更新UI:ListViewForwardGroupMsg, 将第一个QQ群号设置为正在进行的状态
                UpdateListViewForwardGroupMsg(qq: firstQQ);
            });
        }

        private async void btnStartForwardGroupMsg_Click(object forwarder, EventArgs e)
        {
            if (listViewForwardGroupMsgQQ.Items.Count <= 0)
            {
                MessageBox.Show("任务列表为空, 请先添加任务!");
                return;
            }

            // 确保 tbForwardInterval1.Text 是一个有效的整数
            if (!int.TryParse(tbForwardIntervalStart.Text, out int forwardIntervalStart) || forwardIntervalStart <= 0)
            {
                MessageBox.Show("间隔时间开始值必须是一个有效的正整数!");
                return;
            }

            if (!int.TryParse(tbForwardIntervalEnd.Text, out int forwardIntervalEnd) || forwardIntervalEnd <= 0 || forwardIntervalEnd < forwardIntervalStart)
            {
                MessageBox.Show("间隔时间结束值必须是一个有效的正整数且大于等于开始值!");
                return;
            }


            // 确保 tbBatchRecipientCount.Text 是一个有效的整数
            if (!int.TryParse(tbBatchForwardCount.Text, out int batchRecipientCount) || batchRecipientCount <= 0)
            {
                MessageBox.Show("单次转发数量必须是一个有效的正整数!");
                return;
            }

            // 确保 tbAccountTotalForward.Text 是一个有效的整数
            if (!int.TryParse(tbAccountTotalForward.Text, out int accountTotalForward) || accountTotalForward <= 0)
            {
                MessageBox.Show("单号转发数量必须是一个有效的正整数!");
                return;
            }

            if (comboBoxForwardType.SelectedIndex < 0)
            {
                MessageBox.Show("请选择转发类型!");
                return;
            }
            // 转发类型 获取 comboBoxForwardType 的值
            ForwardGroupMsgType msgType = (ForwardGroupMsgType)comboBoxForwardType.SelectedIndex;


            // 重置 转发状态为进行中的都设置为待处理
            await _sendGroupMsgRepository.ResetStatusRunningToNotStartedAsync();

            // 更新按钮状态
            UpdateButtonState(btnStartForwardGroupMsg, btnStopForwardGroupMsg, true);

            _forwardGroupMsgTaskCancellationTokenSource = new CancellationTokenSource();
            var token = _forwardGroupMsgTaskCancellationTokenSource.Token;

            try
            {
                // 开始邀请
                await Task.Run(async () =>
                {
                    // 重新加载QQ列表(包含群列表)
                    QQList = await _qqService.GetQQList();

                    await _forwardGroupMsgServices.Start(QQList, msgType, forwardIntervalStart, forwardIntervalEnd, batchRecipientCount, accountTotalForward, token);
                    MessageBox.Show("转发任务全部完成!");
                }, token);
                // await _inviteAddGroup.Start(textBoxInviteList.Text, inviteInterval);
            }
            catch (OperationCanceledException)
            {
                MessageBox.Show("转发任务已取消!");
            }
            finally
            {
                // 启用开始按钮，禁用停止按钮
                UpdateButtonState(btnStartForwardGroupMsg, btnStopForwardGroupMsg, false);
            }
        }


        private void btnStopForwardGroupMsg_Click(object sender, EventArgs e)
        {
            if (_forwardGroupMsgTaskCancellationTokenSource == null)
            {
                LogManager.Info("暂无转发任务, 无法取消");
                MessageBox.Show("没有正在运行的转发任务");
                return;
            }
            if (_forwardGroupMsgTaskCancellationTokenSource.IsCancellationRequested == false)
            {
                LogManager.Info("转发任务已手动取消");
                _forwardGroupMsgTaskCancellationTokenSource?.Cancel();
                // 更新按钮状态
                UpdateButtonState(btnStartForwardGroupMsg, btnStopForwardGroupMsg, false);
            }
        }
        #endregion
        /// =====================================================转发End============================================================

        /// =====================================================工具函数Start============================================================
        #region  工具函数

        private void SaveControlsContents()
        {
            var dict = new Dictionary<string, string>();
            TraverseControls(this, ctrl =>
            {
                if (ctrl is TextBox textBox)
                {
                    dict[textBox.Name] = textBox.Text;
                }
                if (ctrl is CheckBox checkBox)
                {
                    dict[checkBox.Name] = checkBox.Checked.ToString();
                }
                if (ctrl is ComboBox comboBox)
                {
                    dict[comboBox.Name] = comboBox.SelectedItem.ToString() ?? string.Empty;
                }
                // 保存选项卡
                if (ctrl is TabControl tabControl)
                {
                    dict[tabControl.Name] = tabControl.SelectedTab.Name;
                }

            });

            try
            {
                File.WriteAllText(jsonFilePath, JsonConvert.SerializeObject(dict, Formatting.Indented));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存失败: {ex.Message}");
            }
        }
        /// <summary>
        /// 加载所有控件的内容
        /// </summary>
        private void LoadControlsContents()
        {
            if (!File.Exists(jsonFilePath)) return;

            try
            {
                string json = File.ReadAllText(jsonFilePath);
                var dict = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);
                if (dict == null) return;

                TraverseControls(this, ctrl =>
                {
                    if (ctrl is TextBox textBox && dict.ContainsKey(textBox.Name))
                    {
                        textBox.Text = dict[textBox.Name];
                    }
                    if (ctrl is CheckBox checkBox && dict.ContainsKey(checkBox.Name))
                    {
                        checkBox.Checked = bool.Parse(dict[checkBox.Name]);
                    }
                    if (ctrl is ComboBox comboBox && dict.ContainsKey(comboBox.Name))
                    {
                        comboBox.Text = dict[comboBox.Name];
                    }
                    // 读取选项卡
                    if (ctrl is TabControl tabControl && dict.ContainsKey(tabControl.Name))
                    {
                        //tabControl.SelectedIndex = int.Parse(dict[tabControl.Name]);
                        foreach (TabPage tabPage in tabControl.TabPages)
                        {
                            if (tabPage.Name == dict[tabControl.Name])
                            {
                                tabControl.SelectedTab = tabPage;
                                break;
                            }
                        }
                    }

                });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置文件失败: {ex.Message}");
            }
        }


        /// <summary>
        /// 遍历所有UI控件
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="action"></param>
        private void TraverseControls(Control parent, Action<Control> action)
        {
            foreach (Control ctrl in parent.Controls)
            {
                action(ctrl);
                if (ctrl.HasChildren)
                {
                    TraverseControls(ctrl, action);
                }
            }
        }


        private void UpdateButtonState(Button btnStart, Button btnStop, bool isRunning)
        {
            this.InvokeIfRequired(() =>
            {
                btnStart.Enabled = !isRunning;
                btnStop.Enabled = isRunning;
            });

        }

        /// <summary>
        /// 倒计时
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="seconds"></param>
        /// <param name="token"></param>
        /// <param name="onCountdownComplete"></param>
        /// <returns></returns>
        public async Task StartCountdown(string msg, int seconds, CancellationToken token, Action onCountdownComplete)
        {
            await StartCountdown(msg, seconds, token, "倒计时被取消", onCountdownComplete);
        }
        /// <summary>
        /// 倒计时
        /// </summary>
        /// <param name="msg">内容前缀</param>
        /// <param name="seconds">秒数</param>
        /// <param name="token"></param>
        /// <param name="cancelMsg">被取消提示的内容</param>
        /// <param name="onCountdownComplete">倒计时结束要做的事情</param>
        /// <returns></returns>
        public async Task StartCountdown(string msg, int seconds, CancellationToken token, string cancelMsg, Action onCountdownComplete)
        {
            DateTime endTime = DateTime.Now.Add(TimeSpan.FromSeconds(seconds));
            await StartCountdown(msg, endTime, token, cancelMsg, onCountdownComplete);
        }

        /// <summary>
        /// 倒计时
        /// </summary>
        /// <param name="msg"></param>
        /// <param name="endTime"></param>
        /// <param name="token"></param>
        /// <param name="cancelMsg"></param>
        /// <param name="onCountdownComplete"></param>
        /// <returns></returns>
        public async Task StartCountdown(string msg, DateTime endTime, CancellationToken token, string cancelMsg, Action onCountdownComplete)
        {
            while (DateTime.Now < endTime)
            {
                if (token.IsCancellationRequested)
                {
                    UpdateStatusStrip(cancelMsg);
                    return;
                }

                TimeSpan remaining = endTime - DateTime.Now;
                UpdateStatusStrip($"{msg} {remaining.ToString(@"hh\:mm\:ss")}");

                await Task.Delay(1000, token);
            }
            onCountdownComplete?.Invoke();
        }

        /// <summary>
        /// 更新状态栏信息
        /// </summary>
        /// <param name="message"></param>
        public void UpdateStatusStrip(string message)
        {
            statusStrip1.InvokeIfRequired(() =>
            {
                toolStripStatusLabel2.Text = message;
            });
        }
        #endregion
        /// =====================================================工具函数End============================================================

        /// =====================================================ListViewQQ菜单Start============================================================
        #region ListViewForwardGroupMsg菜单
        private void 置顶ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 将已经勾选的项置顶
            foreach (ListViewItem item in listViewQQ.Items)
            {
                string strHandle = item.SubItems[4].Text;
                if (item.Checked && !string.IsNullOrEmpty(strHandle))
                {
                    IntPtr handle = new IntPtr(Convert.ToInt64(strHandle));
                    // 如果最小化，则先还原
                    Win32Api.ShowWindow(handle, Win32Api.SW_RESTORE);
                    Win32Api.SetForegroundWindow(handle);
                }
            }
        }
        private async void 刷新QQToolStripMenuItem_Click(object sender, EventArgs e)
        {
            await Task.Run(async () =>
            {
                await LoadListViewQQ();
            });
        }
        private async void 获取群数ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            await Task.Run(() =>
            {
                // 将已经勾选的项 获取群数
                listViewQQ.InvokeIfRequired(async () =>
                {
                    foreach (ListViewItem item in listViewQQ.Items)
                    {
                        string qq = item.SubItems[1].Text;
                        int pid = QQPlus.GetQQPid(qq);

                        if (item.Checked && pid != 0)
                        {
                            List<string> groupNumberList = QQPlus.GetGroupList(pid);
                            item.SubItems[3].Text = groupNumberList.Count.ToString();
                            UpdateStatusStrip($"获取群数: QQ:{item.SubItems[1].Text}  最新群数:{item.SubItems[3].Text}个");
                            await Task.Delay(1500); // 延时1秒
                        }
                    }
                });
            });
        }

        private void 导出群号ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            List<ListViewItem> checkedItems = new List<ListViewItem>();
            foreach (ListViewItem item in listViewQQ.Items)
            {
                if (item.Checked)
                { // 检查是否被勾选
                    checkedItems.Add(item);
                }
            }

            if (checkedItems.Count <= 0)
            {
                MessageBox.Show("请先勾选需要导出群号的QQ");
                return;
            }

            // 获取上次保存的目录
            string lastSavedPath = Properties.Settings.Default.LastSavedDirectory;

            using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
            {
                folderBrowserDialog.Description = "选择保存群号的文件夹";

                // 如果上次保存的目录存在，则设置为初始目录
                if (!string.IsNullOrEmpty(lastSavedPath) && Directory.Exists(lastSavedPath))
                {
                    folderBrowserDialog.SelectedPath = lastSavedPath;
                }

                if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
                {
                    string selectedPath = folderBrowserDialog.SelectedPath;

                    // 遍历选中的QQ号
                    foreach (ListViewItem item in listViewQQ.Items)
                    {
                        if (item.Checked)
                        {
                            string qq = item.SubItems[1].Text;

                            // 从 QQList 中获取群号
                            List<string> groupNumberList = QQList.FirstOrDefault(x => x.QQ == qq)?.GroupList;

                            if (groupNumberList != null && groupNumberList.Count > 0)
                            {
                                // 构造文件路径，文件名为 QQ号.txt
                                string filePath = Path.Combine(selectedPath, $"{qq}.txt");

                                // 将群号写入文件
                                File.WriteAllLines(filePath, groupNumberList);
                            }
                        }
                    }

                    MessageBox.Show($"群号已成功导出到文件夹: {selectedPath}");

                    // 保存当前选择的目录为上次保存的目录
                    Properties.Settings.Default.LastSavedDirectory = selectedPath;
                    Properties.Settings.Default.Save();

                    // 询问用户是否需要打开保存的目录
                    var result = MessageBox.Show("是否需要打开保存的目录？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (result == DialogResult.Yes)
                    {
                        // 打开保存的目录
                        Process.Start("explorer.exe", selectedPath);
                    }
                }
            }
        }


        private void 全选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listViewQQ.InvokeIfRequired(() =>
            {
                foreach (ListViewItem item in listViewQQ.Items)
                {
                    item.Checked = true;
                }
            });
        }
        private void 全部显示ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowOrHideQQMainWindows(Win32Api.SW_RESTORE);
        }
        private void 全部隐藏ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ShowOrHideQQMainWindows(Win32Api.SW_HIDE);
        }

        private void 反选ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            listViewQQ.InvokeIfRequired(() =>
            {
                foreach (ListViewItem item in listViewQQ.Items)
                {
                    item.Checked = !item.Checked;
                }
            });
        }

        private void 位置左上ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MoveQQMainWindowsToPosition(Win32Api.SW_RESTORE, 0, 0);
        }

        private void 位置右上ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            MoveQQMainWindowsToPosition(Win32Api.SW_RESTORE, Screen.PrimaryScreen.Bounds.Width, 0);
        }

        private void 结束进程ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            TerminateListViewQQSelectedProcesses();
        }

        /// <summary>
        /// 移动QQ主窗口到指定位置
        /// </summary>
        /// <param name="showCommand"></param>
        /// <param name="targetX"></param>
        /// <param name="targetY"></param>
        private void MoveQQMainWindowsToPosition(int showCommand, int targetX, int targetY)
        {
            listViewQQ.InvokeIfRequired(() =>
            {
                foreach (ListViewItem item in listViewQQ.Items)
                {
                    if (!item.Checked) continue;

                    IntPtr handle = GetListViewQQHandle(item);
                    if (handle == IntPtr.Zero) continue;

                    try
                    {
                        Win32Api.MoveWindowsToPosition(handle, targetX, targetY);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"移动窗口时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            });
        }


        /// <summary>
        /// 显示或隐藏QQ主窗口
        /// </summary>
        /// <param name="showCommand"> Win32Api.Hide</param>
        /// <param name="allHide">全部隐藏:true 仅勾选隐藏:false</param>
        private void ShowOrHideQQMainWindows(int showCommand, bool allHide = false)
        {
            // 边界条件：检查 listViewQQ 是否为空
            if (listViewQQ == null)
            {
                LogManager.Error("listViewQQ 为 null，无法执行显示或隐藏操作。");
                return;
            }

            listViewQQ.InvokeIfRequired(() =>
            {
                // 边界条件：检查 listViewQQ.Items 是否为空
                if (listViewQQ.Items.Count == 0)
                {
                    LogManager.Error("listViewQQ 中没有项目，无法执行显示或隐藏操作。");
                    return;
                }
                foreach (ListViewItem item in listViewQQ.Items)
                {
                    IntPtr handle = GetListViewQQHandle(item);
                    // 边界条件：检查 handle 是否有效
                    if (handle == IntPtr.Zero)
                    {
                        LogManager.Error($"无法获取 ListViewItem 的句柄: {item.Text}");
                        continue;
                    }

                    // 根据 allHide 和 item.Checked 决定是否执行操作
                    if (allHide || item.Checked)
                    {
                        try
                        {
                            Win32Api.ShowWindow(handle, showCommand);
                        }
                        catch (Exception ex)
                        {
                            LogManager.Error($"显示或隐藏窗口时出错: {ex.Message}");
                        }
                    }
                }
            });
        }

        /// <summary>
        /// 获取ListViewQQ指定项的句柄
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        private IntPtr GetListViewQQHandle(ListViewItem item)
        {
            try
            {
                return new IntPtr(Convert.ToInt64(item.SubItems[4].Text));
            }
            catch (Exception ex)
            {
                MessageBox.Show($"获取窗口句柄时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return IntPtr.Zero;
            }
        }
        /// <summary>
        /// 结束选中项的QQ
        /// </summary>
        private void TerminateListViewQQSelectedProcesses()
        {
            listViewQQ.InvokeIfRequired(async () =>
            {
                foreach (ListViewItem item in listViewQQ.Items)
                {
                    if (!item.Checked) continue;

                    IntPtr handle = GetListViewQQHandle(item);
                    if (handle == IntPtr.Zero) continue;

                    try
                    {
                        int processId;
                        Win32Api.GetWindowThreadProcessId(handle, out processId);
                        Process process = Process.GetProcessById((int)processId);
                        process.Kill();
                        // 重新加载QQ表格
                        await LoadListViewQQ();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($"结束进程时出错: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            });
        }

        private void tabControl1_Selected(object sender, TabControlEventArgs e)
        {
            InitTabControl();
            // 保存控件内容
            SaveControlsContents();
        }
        #endregion
        /// =====================================================ListViewQQ菜单End============================================================
        /// =====================================================ListViewForwardGroupMsg菜单Start================================================
        #region  ListViewForwardGroupMsg菜单Start
        private async void 失败改正常ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            await _forwardGroupMsgRepository.UpdateFaildToNotStart();
            List<ForwardGroupMsgModel> forwardGroupMsgModels = await _forwardGroupMsgRepository.GetAllAsync();
            // 重新加载表格
            UpdateListViewForwardGroupMsg(forwardGroupMsgModels);
        }

        private void listViewForwardGroupMsgQQ_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            // 获取当前选中的行
            ListViewItem item = listViewForwardGroupMsgQQ.GetItemAt(e.X, e.Y);
            if (item == null) return;
            if (item.SubItems.Count > 0)
            {
                // 获取当前行的群号
                string qq = item.SubItems[1].Text;
                if (string.IsNullOrEmpty(qq)) return;
                // 更新ForwardGroupMsg中的数据
                UpdateListViewForwardGroupMsg(qq);
            }
        }
        #endregion
        /// =====================================================ListViewForwardGroupMsg菜单End==================================================

        /// =====================================================邀请End==================================================
        #region 邀请功能模块
        private async void btnInviteSuccessZero_Click(object sender, EventArgs e)
        {
            await _inviteGroupQQRepository.UpdateInviteSuccessZero();
            // 重新加载表格
            UpdateListViewInviteGroupQQ();
        }

        private async void btnAddInviteTask_Click(object sender, EventArgs e)
        {
            // 刷新添加QQ列表
            // 处理 listViewInviteQQ 列表
            // 判断 listViewQQ 的选中相
            // 获取所有勾选的 ListViewItem
            List<ListViewItem> checkedItems = new List<ListViewItem>();
            foreach (ListViewItem item in listViewQQ.Items)
            {
                if (item.Checked)
                { // 检查是否被勾选
                    checkedItems.Add(item);
                }
            }

            if (checkedItems.Count <= 0)
            {
                MessageBox.Show("请先勾选最左侧QQ列表");
                return;
            }
            // 判断邀请任务中的QQ列表是否为空
            List<InviteGroupQQModel> inviteGroupQQModels = await _inviteGroupQQRepository.GetAllAsync();
            if (inviteGroupQQModels.Count() > 0)
            {
                var result = MessageBox.Show("已有邀请任务，删除后无法恢复\n\n\t是否确定删除？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    // UI:删除邀请任务:QQ列表
                    listViewInviteGroupQQ.Items.Clear();
                    // 数据库:清空邀请任务:invite_group_qq
                    await _inviteGroupQQRepository.ClearTableAsync();


                    // UI:删除邀请任务:群列表
                    listViewInviteGroup.Items.Clear();
                    // 数据库:清空邀请任务:invite_group
                    await _inviteGroupRepository.ClearTableAsync();

                    LogManager.Info($"[添加邀请任务] 清空邀请任务:InviteGroupQQ和InviteGroup的数据库, 开始新的任务");
                }
                else
                {
                    return;
                }
            }

            await Task.Run(async () =>
            {
                string firstQQ = null;
                inviteGroupQQModels = new List<InviteGroupQQModel>();
                for (int i = 0; i < checkedItems.Count; i++)
                {
                    ListViewItem item = checkedItems[i];

                    string qq = item.SubItems[1].Text;

                    // 插入到 invite_group_qq 表中
                    InviteGroupQQModel inviteGroupQQModel = new InviteGroupQQModel();

                    inviteGroupQQModel.QQ = qq;
                    inviteGroupQQModel.InviteNumber = 0;
                    inviteGroupQQModel.CreateTime = DateTime.Now;
                    inviteGroupQQModel.UpdateTime = DateTime.Now;

                    await _inviteGroupQQRepository.AddOrUpdateAsync(inviteGroupQQModel);
                    if (i == 0)
                    {
                        // 将第一个QQ设置为正在进行的状态
                        firstQQ = qq;
                    }
                    inviteGroupQQModels.Add(inviteGroupQQModel);
                }
                // 更新UI:ListViewInviteGroupQQ, 将第一个QQ设置为正在进行的状态
                UpdateListViewInviteGroupQQ(inviteGroupQQModels, firstQQ);
                // 更新UI:ListViewInviteGroup, 将第一个QQ群号设置为正在进行的状态
                UpdateListViewInviteGroup(qq: firstQQ);
            });
        }

        private void listViewInviteGroupQQ_MouseDoubleClick(object sender, MouseEventArgs e)
        {

            // 获取当前选中的行
            ListViewItem item = listViewInviteGroupQQ.GetItemAt(e.X, e.Y);
            if (item == null) return;
            if (item.SubItems.Count > 0)
            {
                // 获取当前行的群号
                string qq = item.SubItems[1].Text;
                if (string.IsNullOrEmpty(qq)) return;
                // 更新 InviteGroup 中的数据
                UpdateListViewInviteGroup(qq);
            }
        }
        private async void UpdateListViewInviteGroup(string qq)
        {
            if (string.IsNullOrEmpty(qq))
            {
                LogManager.Error($"[UpdateListViewInviteGroup] UI:更新邀请任务失败: qq为空");
                return;
            }
            try
            {
                // 获取该QQ的群列表
                List<InviteGroupModel> inviteGroupModels = await _inviteGroupRepository.GetByQQAsync(qq);
                if (inviteGroupModels == null || inviteGroupModels.Count() <= 0)
                {
                    // 数据库没有该QQ的群列表, 重新获取
                    UpdateListViewInviteGroup(qq, null);
                }
                else
                {
                    // 默认该QQ的第一个群号为进行时
                    UpdateListViewInviteGroup(inviteGroupModels, inviteGroupModels.FirstOrDefault()?.GroupNumber);
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewInviteGroup] UI:更新邀请任务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新邀请任务群列表
        /// </summary>
        /// <param name="inviteGroupModel"></param>
        public async void UpdateListViewInviteGroup(InviteGroupModel inviteGroupModel)
        {
            if (inviteGroupModel == null)
            {
                LogManager.Error($"[UpdateListViewInviteGroup] UI:更新邀请任务失败: forwardGroupMsgModel为空");
                return;
            }

            try
            {
                List<InviteGroupModel> inviteGroupModels = await _inviteGroupRepository.GetByQQAsync(inviteGroupModel.QQ);
                if (inviteGroupModels == null || inviteGroupModels.Count() <= 0)
                {
                    LogManager.Error($"[UpdateListViewInviteGroup] UI:更新邀请任务失败: qq:{inviteGroupModel.QQ}的群为空");
                    return;
                }
                UpdateListViewInviteGroup(inviteGroupModels, inviteGroupModel.GroupNumber);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewInviteGroup] UI:更新邀请任务失败: {ex.Message}");
            }
        }

        public async void UpdateListViewInviteGroup(string qq = null, string groupNumber = null)
        {
            // 获取对应QQ的群列表
            List<InviteGroupModel> inviteGroupModels = new List<InviteGroupModel>();

            // 获取所有转发任务QQ
            List<InviteGroupQQModel> inviteGroupQQModels = await _inviteGroupQQRepository.GetAllAsync();
            if (inviteGroupQQModels.Count() <= 0)
            {
                LogManager.Info($"[UpdateListViewInviteGroup] 暂无邀请任务!");
                return;
            }


            List<InviteGroupModel> fristQQGroupList = new List<InviteGroupModel>();

            foreach (var inviteGroupQQModel in inviteGroupQQModels)
            {

                // 从QQList获取qq对应的 QQ的群列表
                var item = QQList.FirstOrDefault(x => x.QQ == inviteGroupQQModel.QQ);
                if (item == null)
                {
                    LogManager.Error($"[UpdateListViewInviteGroup] UI:更新邀请任务失败: qq:{inviteGroupQQModel.QQ}的群为空");
                    continue;
                }
                // 组装QQ群列表
                List<InviteGroupModel> currentQQGroupList = new List<InviteGroupModel>();
                foreach (var group in item.GroupList)
                {


                    InviteGroupModel inviteGroupModel = new InviteGroupModel
                    {
                        QQ = item.QQ,
                        GroupNumber = group,
                        Status = InviteGroupStatus.Pending, // 默认:待处理
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };
                    currentQQGroupList.Add(inviteGroupModel);
                    inviteGroupModels.Add(inviteGroupModel);
                }
            }

            // 批量插入 将群列表存储到数据库
            await _inviteGroupRepository.BulkInsertAsync(inviteGroupModels);


            if (string.IsNullOrEmpty(qq))
            {
                // 如果qq为空,则取出任务列表第一个QQ
                qq = inviteGroupQQModels.FirstOrDefault()?.QQ;
            }

            // 从数据库读取当前QQ的群列表
            List<InviteGroupModel> inviteGroupList = await _inviteGroupRepository.GetByQQAsync(qq);
            if (inviteGroupList == null)
            {
                LogManager.Error($"[UpdateListViewInviteGroup]  qq:{qq} 从数据库读取当前QQ的群列表失败");
                return;
            }

            if (groupNumber == null)
            {
                // 取出 inviteGroupList 的第一个元素作为groupNumber
                groupNumber = inviteGroupList.FirstOrDefault().GroupNumber;
            }
            // 更新UI;将当前QQ的群列表展示出来
            UpdateListViewInviteGroup(inviteGroupList, groupNumber);
        }
        /// <summary>
        /// 更新邀请任务群列表
        /// </summary>
        /// <param name="inviteGroupModels"></param>
        /// <param name="groupNumber"></param>
        public void UpdateListViewInviteGroup(List<InviteGroupModel> inviteGroupModels, string groupNumber = null)
        {
            // 自动识别线程, 更新UI
            listViewInviteGroup.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewInviteGroup.BeginUpdate();
                listViewInviteGroup.SuspendLayout(); // 禁用布局更新
                listViewInviteGroup.Items.Clear();

                if (string.IsNullOrEmpty(groupNumber))
                {
                    // 默认 获取 listViewInviteGroup 第一个的群
                    groupNumber = inviteGroupModels.FirstOrDefault().GroupNumber;
                }

                // 批量添加项
                var itemsToAdd = inviteGroupModels.Select((forwardGroupMsg, index) => CreateListViewInviteGroupItem(forwardGroupMsg, index + 1, groupNumber)).ToList();
                listViewInviteGroup.Items.AddRange(itemsToAdd.ToArray());


                // 将列表滚动到 newItem.BackColor = Color.LightSalmon;
                var targetItem = listViewInviteGroup.Items.Cast<ListViewItem>()
                    .FirstOrDefault(x => x.SubItems[1].Text == groupNumber);

                if (targetItem != null)
                {
                    // 直接定位到目标项的下一个项（如果存在）
                    int itemIndex = listViewInviteGroup.Items.IndexOf(targetItem);
                    // 滚动到将item的下一个的item
                    if (itemIndex < listViewInviteGroup.Items.Count - 1)
                    {
                        listViewInviteGroup.Items[itemIndex + 1].EnsureVisible();
                    }
                    else
                    {
                        // 如果是最后一项，直接滚动到自身
                        targetItem.EnsureVisible();
                    }
                }

                listViewInviteGroup.ResumeLayout(); // 启用布局更新
                listViewInviteGroup.EndUpdate();


            });
        }

        /// <summary>
        /// 创建一个 InviteGroup Item
        /// </summary>
        /// <param name="inviteGroup"></param>
        /// <param name="index"></param>
        /// <param name="groupNumber">如果groupNumber不为空则设置为正在进行的状态</param>
        /// <returns></returns>
        private ListViewItem CreateListViewInviteGroupItem(InviteGroupModel inviteGroup, int index, string groupNumber)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(inviteGroup.GroupNumber);
            newItem.SubItems.Add(inviteGroup.Status.ToChineseString());

            if (inviteGroup.Status == InviteGroupStatus.Success)
            {
                newItem.BackColor = Color.LightGreen;
            }
            else if (inviteGroup.Status == InviteGroupStatus.Bebeing || string.Equals(inviteGroup.GroupNumber, groupNumber))
            {
                newItem.BackColor = Color.LightSalmon;
            }
            else if (inviteGroup.Status == InviteGroupStatus.Failed)
            {
                newItem.BackColor = Color.LightCoral;
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }


            return newItem;
        }

        /// <summary>
        /// 更新邀请任务QQ列表
        /// </summary>
        /// <param name="inviteGroupQQModel"></param>
        public async void UpdateListViewInviteGroupQQ(InviteGroupQQModel inviteGroupQQModel = null, string qq = null)
        {
            List<InviteGroupQQModel> inviteGroupQQModels = new List<InviteGroupQQModel>();
            try
            {
                if (inviteGroupQQModel == null)
                {
                    // 从数据库加载邀请任务
                    inviteGroupQQModels = await _inviteGroupQQRepository.GetAllAsync();
                    if (inviteGroupQQModels.Count() <= 0)
                    {
                        return;
                    }
                }
                else
                {
                    inviteGroupQQModels.Add(inviteGroupQQModel);
                }
                if (qq == null)
                {
                    // 默认第一个QQ为进行时
                    qq = inviteGroupQQModels.FirstOrDefault()?.QQ;
                }
                UpdateListViewInviteGroupQQ(inviteGroupQQModels, qq);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewInviteGroupQQ] UI:更新转发任务失败: {ex.Message}");
            }
        }

        private void UpdateListViewInviteGroupQQ(List<InviteGroupQQModel> inviteGroupQQModels, string qq)
        {
            // 自动识别线程, 更新UI
            listViewInviteGroupQQ.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewInviteGroupQQ.BeginUpdate();
                listViewInviteGroupQQ.SuspendLayout(); // 禁用布局更新
                listViewInviteGroupQQ.Items.Clear();

                // 批量添加项
                var itemsToAdd = inviteGroupQQModels.Select((inviteGroupQQ, index) => CreateListViewInviteGroupQQItem(inviteGroupQQ, index + 1, qq)).ToList();
                listViewInviteGroupQQ.Items.AddRange(itemsToAdd.ToArray());

                listViewInviteGroupQQ.ResumeLayout(); // 启用布局更新
                listViewInviteGroupQQ.EndUpdate();
            });
        }

        private ListViewItem CreateListViewInviteGroupQQItem(InviteGroupQQModel inviteGroupQQ, int index, string qq = null)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(inviteGroupQQ.QQ);
            newItem.SubItems.Add(inviteGroupQQ.InviteSuccessCount.ToString());
            newItem.SubItems.Add(inviteGroupQQ.InviteNumber.ToString());

            if (qq != null && string.Equals(inviteGroupQQ.QQ, qq))
            {
                newItem.BackColor = Color.LightSalmon; // 统一颜色设置
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }

            return newItem;
        }

        private async void btnStartInvite_Click(object sender, EventArgs e)
        {
            if (listViewInviteGroupQQ.Items.Count <= 0)
            {
                MessageBox.Show("任务列表为空, 请先添加任务!");
                return;
            }

            // 确保 textBoxInviteInterval.Text 是一个有效的整数
            if (!int.TryParse(textBoxInviteInterval.Text, out int inviteInterval) || inviteInterval <= 0)
            {
                MessageBox.Show("邀请间隔必须是一个有效的正整数!");
                return;
            }

            // 确保 textBoxInviteNumber.Text 是一个有效的整数
            if (!int.TryParse(textBoxInviteNumber.Text, out int inviteNumber) || inviteNumber <= 0)
            {
                MessageBox.Show("邀请数量必须是一个有效的正整数!");
                return;
            }

            if (string.IsNullOrEmpty(textBoxInviteList.Text))
            {
                MessageBox.Show("邀请名单不能为空!");
                return;
            }


            // 重置 邀请群状态为进行中的都设置为待处理
            await _inviteGroupRepository.ResetStatusToPendingAsync();

            // 更新按钮状态
            UpdateButtonState(btnStartInvite, btnStopInvite, true);

            _inviteGroupTaskCancellationTokenSource = new CancellationTokenSource();
            var token = _inviteGroupTaskCancellationTokenSource.Token;
            string invitedQQ = textBoxInviteList.Text.Trim();
            try
            {
                // 开始邀请
                await Task.Run(async () =>
                {

                    await _inviteGroupServices.Start(invitedQQ, inviteInterval, inviteNumber, token);
                    LogManager.Info("邀请任务执行结束");
                    MessageBox.Show("邀请任务全部完成!");
                }, token);
            }
            catch (OperationCanceledException)
            {
                LogManager.Info("邀请任务已取消!");
                MessageBox.Show("邀请任务已取消!");
            }
            finally
            {
                LogManager.Info($"[邀请任务] 任务已结束, 修改按钮状态");
                // 启用开始按钮，禁用停止按钮
                UpdateButtonState(btnStartInvite, btnStopInvite, false);
            }
        }

        private void btnStopInvite_Click(object sender, EventArgs e)
        {

            if (_inviteGroupTaskCancellationTokenSource == null)
            {
                LogManager.Info("暂无邀请任务, 无法取消");
                MessageBox.Show("没有正在运行的邀请任务");
                return;
            }
            if (_inviteGroupTaskCancellationTokenSource.IsCancellationRequested == false)
            {
                LogManager.Info("邀请任务已手动取消");
                _inviteGroupTaskCancellationTokenSource?.Cancel();
                // 更新按钮状态
                UpdateButtonState(btnStartInvite, btnStopInvite, false);
            }
        }
        #endregion
        /// =====================================================邀请End==================================================
        /// =====================================================加群End==================================================
        #region 加群功能模块
        private void btnImportGroupNumber_Click(object sender, EventArgs e)
        {
            // 打开文件对话框, 选择一个txt文件
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Text Files (*.txt)|*.txt";
            openFileDialog.Title = "选择群号文件";
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                // 读取文件内容
                string[] lines = File.ReadAllLines(filePath);
                // 添加到群号列表
                listViewAddGroup.InvokeIfRequired(async () =>
                {
                    // 防止闪烁
                    listViewAddGroup.BeginUpdate();
                    // 清空历史
                    listViewAddGroup.Items.Clear();

                    // 创建一个列表来存储所有的 AddGroupInfo 对象
                    var addGroups = new List<AddGroupModel>();
                    // 遍历每一行
                    foreach (string line in lines)
                    {
                        // 提取群号
                        string groupNumber = line.Trim();
                        ListViewItem newItem = new ListViewItem((listViewAddGroup.Items.Count + 1).ToString());
                        newItem.SubItems.Add(groupNumber);
                        newItem.SubItems.Add(AddGroupStatus.NotStart.ToChineseString());
                        // newItem.BackColor = Color.LightSalmon;
                        // 1.先将 任务QQ 添加到 listViewInviteQQ 中
                        listViewAddGroup.Items.Add(newItem);

                        // 创建 AddGroupInfo 对象并添加到列表中
                        var addGroup = new AddGroupModel
                        {
                            GroupNumber = groupNumber,
                            Status = AddGroupStatus.NotStart,
                            CreateTime = DateTime.Now,
                            UpdateTime = DateTime.Now
                        };
                        addGroups.Add(addGroup);
                    }
                    // 绘
                    listViewAddGroup.EndUpdate();

                    // 批量插入数据库
                    await _addGroupRepository.AddOrUpdateBatchAsync(addGroups);

                });
            }
        }
        private async void btnAddAddGroupTask_Click(object sender, EventArgs e)
        {

            // 获取所有勾选的 ListViewItem
            List<ListViewItem> checkedItems = new List<ListViewItem>();
            foreach (ListViewItem item in listViewQQ.Items)
            {
                if (item.Checked)
                { // 检查是否被勾选
                    checkedItems.Add(item);
                }
            }

            if (checkedItems.Count <= 0)
            {
                MessageBox.Show("请先勾选最左侧QQ列表");
                return;
            }
            // 判断邀请功能中的QQ列表是否为空
            List<AddGroupQQModel> addGroupQQs = await _addGroupQQRepository.GetAllAsync();
            if (addGroupQQs.Count() > 0)
            {
                var result = MessageBox.Show("已有加群任务，删除后无法恢复\n\n\t是否确定删除？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    // 清空加群任务:addGroupQQ数据库, 开始新的任务
                    await _addGroupQQRepository.ClearTableAsync();

                    // 删除加群任务:QQ列表
                    listViewAddGroupQQ.Items.Clear();
                    // 删除记录qq
                    _addGroupServices.SaveAddGroudProgress("");
                    //Properties.Settings.Default.AddGroupCurrentQQ = "";
                    //// 删除当前正在执行任务的QQ
                    //Properties.Settings.Default.Save();

                    LogManager.Info($"[添加加群任务] 清空加群任务:AddGroupQQ的数据库, 开始新的任务");
                }
                else
                {
                    return;
                }
            }

            await Task.Run(async () =>
            {
                addGroupQQs = new List<AddGroupQQModel>();
                foreach (var item in checkedItems)
                {
                    string qq = item.SubItems[1].Text;

                    // 插入到 add_group_qq 表中
                    AddGroupQQModel addGroupQQModel = new AddGroupQQModel();
                    addGroupQQModel.QQ = qq;
                    addGroupQQModel.CurrentBatch = AddGroupQQStatus.Batch1;
                    addGroupQQModel.CurrentBatchAddCount = 0;
                    addGroupQQModel.TotalAdd = 0;
                    addGroupQQModel.CreateTime = DateTime.Now;
                    addGroupQQModel.UpdateTime = DateTime.Now;
                    await _addGroupQQRepository.AddOrUpdateAsync(addGroupQQModel);
                    addGroupQQs.Add(addGroupQQModel);
                }
                // 更新UI:ListViewAddGroupQQ
                UpdateListViewAddGroupQQ(addGroupQQs);
                // 更新UI:ListViewAddGroup
                UpdateListViewAddGroup();
            });

        }

        private async void btnStartAddGroup_Click(object sender, EventArgs e)
        {

            if (listViewAddGroup.Items.Count <= 0)
            {
                MessageBox.Show("群号列表为空, 请先导入群号!");
                return;
            }

            if (listViewAddGroupQQ.Items.Count <= 0)
            {
                MessageBox.Show("任务列表为空, 请先添加任务!");
                return;
            }

            // 确保 textBoxAddGroupNumber1 和 textBoxAddGroupNumber2 是有效的整数
            if (!int.TryParse(textBoxAddGroupNumber1.Text, out int addGroupNumber1) || addGroupNumber1 <= 0)
            {
                MessageBox.Show("批次1的群数必须是一个有效的正整数!");
                return;
            }

            if (!int.TryParse(textBoxAddGroupNumber2.Text, out int addGroupNumber2) || addGroupNumber2 <= 0)
            {
                MessageBox.Show("批次2的群数必须是一个有效的正整数!");
                return;
            }

            // 确保 textBoxAddGroupIntervalTimeStart 和 textBoxAddGroupIntervalTimeEnd 是有效的整数
            if (!int.TryParse(textBoxAddGroupIntervalTimeStart.Text, out int intervalStart) || intervalStart <= 0)
            {
                MessageBox.Show("间隔时间开始值必须是一个有效的正整数!");
                return;
            }

            if (!int.TryParse(textBoxAddGroupIntervalTimeEnd.Text, out int intervalEnd) || intervalEnd <= 0 || intervalEnd < intervalStart)
            {
                MessageBox.Show("间隔时间结束值必须是一个有效的正整数且大于等于开始值!");
                return;
            }

            // 确保 textBoxAddGroupSleep1 和 textBoxAddGroupSleep2 是有效的整数
            if (!int.TryParse(textBoxAddGroupSleep1.Text, out int sleep1) || sleep1 <= 0)
            {
                MessageBox.Show("批次1的休息时间必须是一个有效的正整数!");
                return;
            }

            if (!int.TryParse(textBoxAddGroupSleep2.Text, out int sleep2) || sleep2 <= 0)
            {
                MessageBox.Show("批次2的休息时间必须是一个有效的正整数!");
                return;
            }


            // 更新按钮状态
            UpdateButtonState(btnStartAddGroup, btnStopAddGroup, true);

            // 初始化 CancellationTokenSource
            _addGroupTaskCancellationTokenSource = new CancellationTokenSource();
            var token = _addGroupTaskCancellationTokenSource.Token;

            try
            {
                // 开始加群任务
                await Task.Run(async () =>
                {
                    // 重新加载QQ列表(包含群列表)
                    QQList = await _qqService.GetQQList();

                    await _addGroupServices.Start(QQList, addGroupNumber1, addGroupNumber2, intervalStart, intervalEnd, sleep1, sleep2, token);
                    LogManager.Info("加群任务执行结束");
                    MessageBox.Show("加群任务全部完成!");
                }, token);
            }
            catch (OperationCanceledException)
            {
                MessageBox.Show("加群任务已取消!");
            }
            finally
            {
                // 更新按钮状态
                UpdateButtonState(btnStartAddGroup, btnStopAddGroup, false);
            }
        }

        private void btnStopAddGroup_Click(object sender, EventArgs e)
        {
            if (_addGroupTaskCancellationTokenSource == null)
            {
                LogManager.Info("暂无加群任务, 无法取消");
                MessageBox.Show("没有正在运行的加群任务");
                return;
            }
            if (_addGroupTaskCancellationTokenSource.IsCancellationRequested == false)
            {
                LogManager.Info("加群任务已手动取消");
                CancelTask(_addGroupTaskCancellationTokenSource);
                // 更新按钮状态
                UpdateButtonState(btnStartAddGroup, btnStopAddGroup, false);
            }
        }


        /// <summary>
        /// 更新加群任务QQ列表
        /// </summary>
        /// <param name="addGroupQQModel"></param>
        public async void UpdateListViewAddGroupQQ(AddGroupQQModel addGroupQQModel = null, string qq = null)
        {
            List<AddGroupQQModel> addGroupQQModels = new List<AddGroupQQModel>();
            try
            {

                // 从数据库加载加群任务
                addGroupQQModels = await _addGroupQQRepository.GetAllAsync();
                if (addGroupQQModels.Count() <= 0)
                {
                    LogManager.Info($"[UpdateListViewAddGroupQQ] 暂无加群任务!");
                    return;
                }

                if (addGroupQQModel == null)
                {
                    if (qq == null)
                    {
                        // 默认第一个QQ为进行时
                        qq = addGroupQQModels.FirstOrDefault()?.QQ;
                    }
                }
                else
                {
                    qq = addGroupQQModel.QQ;
                }

                UpdateListViewAddGroupQQ(addGroupQQModels, qq);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewAddGroupQQ] UI:更新转发任务失败: {ex.Message}");
            }
        }

        private void UpdateListViewAddGroupQQ(List<AddGroupQQModel> addGroupQQModels, string qq = null)
        {
            // 自动识别线程, 更新UI
            listViewAddGroupQQ.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewAddGroupQQ.BeginUpdate();
                listViewAddGroupQQ.SuspendLayout(); // 禁用布局更新
                listViewAddGroupQQ.Items.Clear();

                // 批量添加项
                var itemsToAdd = addGroupQQModels.Select((addGroupQQ, index) => CreateListViewAddGroupQQItem(addGroupQQ, index + 1, qq)).ToList();
                listViewAddGroupQQ.Items.AddRange(itemsToAdd.ToArray());

                listViewAddGroupQQ.ResumeLayout(); // 启用布局更新
                listViewAddGroupQQ.EndUpdate();
            });
        }

        private ListViewItem CreateListViewAddGroupQQItem(AddGroupQQModel addGroupQQ, int index, string qq = null)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(addGroupQQ.QQ);
            newItem.SubItems.Add(addGroupQQ.CurrentBatch.ToChineseString());
            newItem.SubItems.Add(addGroupQQ.CurrentBatchAddCount.ToString());
            newItem.SubItems.Add(addGroupQQ.TotalAdd.ToString());

            if (qq != null && string.Equals(addGroupQQ.QQ, qq))
            {
                newItem.BackColor = Color.LightSalmon; // 统一颜色设置
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }
            return newItem;
        }

        /// <summary>
        /// 更新加群任务群列表
        /// </summary>
        /// <param name="qq"></param>
        public async void UpdateListViewAddGroup(string qq)
        {
            if (string.IsNullOrEmpty(qq))
            {
                LogManager.Error($"[UpdateListViewAddGroup] UI:更新加群任务失败: qq为空");
                return;
            }
            try
            {
                // 获取该QQ的群列表
                List<AddGroupModel> addGroupModels = await _addGroupRepository.GetByQQAsync(qq);
                if (addGroupModels == null || addGroupModels.Count() <= 0)
                {
                    // 数据库没有该QQ的群列表, 重新获取
                    UpdateListViewAddGroup(qq, null);
                }
                else
                {
                    // 默认该QQ的第一个群号为进行时
                    UpdateListViewAddGroup(addGroupModels, addGroupModels.FirstOrDefault()?.GroupNumber);
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewAddGroup] UI:更新加群任务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新加群任务群列表
        /// </summary>
        /// <param name="addGroupQQModel"></param>
        public async void UpdateListViewAddGroup(AddGroupModel addGroupModel)
        {
            if (addGroupModel == null)
            {
                LogManager.Error($"[UpdateListViewAddGroup] UI:更新加群任务失败: addGroupModel为空");
                return;
            }

            try
            {
                List<AddGroupModel> addGroupModels = await _addGroupRepository.GetAllAsync();
                if (addGroupModels == null || addGroupModels.Count() <= 0)
                {
                    LogManager.Error($"[UpdateListViewAddGroup] UI:更新加群任务失败: qq:{addGroupModel.QQ}的群为空");
                    return;
                }
                UpdateListViewAddGroup(addGroupModels, addGroupModel.GroupNumber);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewAddGroup] UI:更新加群任务失败: {ex.Message}");
            }
        }


        /// <summary>
        /// 更新加群任务群列表
        /// </summary>
        /// <param name="qq"></param>
        /// <param name="groupNumber"></param>
        public async void UpdateListViewAddGroup(string qq = null, string groupNumber = null)
        {

            // 获取所有待加群号
            List<AddGroupModel> addGroupModels = await _addGroupRepository.GetAllAsync();
            if (addGroupModels.Count() <= 0)
            {
                LogManager.Info($"[UpdateListViewAddGroup] 暂无待加群号!");
                return;
            }

            // 更新UI;将当前QQ的群列表展示出来
            UpdateListViewAddGroup(addGroupModels);

        }


        /// <summary>
        /// 更新加群任务群列表
        /// </summary>
        /// <param name="addGroupModels"></param>
        /// <param name="groupNumber"></param>
        public void UpdateListViewAddGroup(List<AddGroupModel> addGroupModels, string groupNumber = null)
        {

            // 自动识别线程, 更新UI
            listViewAddGroup.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewAddGroup.BeginUpdate();
                listViewAddGroup.SuspendLayout(); // 禁用布局更新
                listViewAddGroup.Items.Clear();

                // 批量添加项
                var itemsToAdd = addGroupModels.Select((addGroup, index) => CreateListViewAddGroupItem(addGroup, index + 1, groupNumber)).ToList();
                listViewAddGroup.Items.AddRange(itemsToAdd.ToArray());

                ListViewItem targetItem;
                if (!string.IsNullOrEmpty(groupNumber))
                {
                    // groupNumber 存在，则滚动到该群
                    // 将列表滚动到 newItem.BackColor = Color.LightSalmon;
                    targetItem = listViewAddGroup.Items.Cast<ListViewItem>()
                       .FirstOrDefault(x => x.SubItems[1].Text == groupNumber);
                }
                else
                {
                    // groupNumber 不存在，则滚动到第一个未开始
                    // 将列表滚动到 newItem.BackColor = Color.LightSalmon;
                    targetItem = listViewAddGroup.Items.Cast<ListViewItem>()
                       .FirstOrDefault(x => x.SubItems[2].Text == AddGroupStatus.NotStart.ToChineseString());
                }

                if (targetItem != null)
                {
                    // 直接定位到目标项的下一个项（如果存在）
                    int itemIndex = listViewAddGroup.Items.IndexOf(targetItem);
                    // 滚动到将item的下一个的item
                    if (itemIndex < listViewAddGroup.Items.Count - 1)
                    {
                        listViewAddGroup.Items[itemIndex + 1].EnsureVisible();
                    }
                    else
                    {
                        // 如果是最后一项，直接滚动到自身
                        targetItem.EnsureVisible();
                    }
                }

                listViewAddGroup.ResumeLayout(); // 启用布局更新
                listViewAddGroup.EndUpdate();
            });
        }

        /// <summary>
        /// 创建一个 AddGroup Item
        /// </summary>
        /// <param name="addGroup"></param>
        /// <param name="index"></param>
        /// <param name="groupNumber">如果groupNumber不为空则设置为正在进行的状态</param>
        /// <returns></returns>
        private ListViewItem CreateListViewAddGroupItem(AddGroupModel addGroup, int index, string groupNumber = null)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(addGroup.GroupNumber);
            newItem.SubItems.Add(addGroup.Status.ToChineseString());

            if (addGroup.Status == AddGroupStatus.Success)
            {
                newItem.BackColor = Color.LightGreen;
            }
            else if (addGroup.Status == AddGroupStatus.Running || string.Equals(addGroup.GroupNumber, groupNumber))
            {
                newItem.BackColor = Color.LightSalmon;
            }
            else if (addGroup.Status == AddGroupStatus.Failed)
            {
                newItem.BackColor = Color.LightCoral;
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }
            return newItem;
        }
        /// <summary>
        /// 更新加群QQ
        /// </summary>
        /// <param name="addGroupQQs"></param>
        /// <param name="addGroupQQ"></param>
        public void UpdateAddGroupQQProcess(List<AddGroupQQModel> addGroupQQs, AddGroupQQModel addGroupQQ)
        {
            // 获取当前qq的下一个qq
            int addGroupQQIndex = addGroupQQs.IndexOf(addGroupQQ);
            string qq;
            if (addGroupQQs.Count > addGroupQQIndex + 1)
            {
                // 下一个qq
                qq = addGroupQQs[addGroupQQs.IndexOf(addGroupQQ) + 1].QQ;
            }
            else
            {
                qq = addGroupQQs[0].QQ;
            }
            LogManager.Info($"[更新加群QQ] 当前QQ:{addGroupQQ.QQ} 下一个QQ:{qq}");
            _addGroupServices.SaveAddGroudProgress(qq);
            //Properties.Settings.Default.AddGroupCurrentQQ = qq;
            //// 记住当前正在执行任务的QQ
            //Properties.Settings.Default.Save();
        }



        #endregion

        /// =====================================================加群End==================================================

        /// =====================================================屏蔽End==================================================

        #region 屏蔽功能模块


        private async void btnAddBlockGroupTask_Click(object sender, EventArgs e)
        {
            // 获取所有勾选的 ListViewItem
            List<ListViewItem> checkedItems = new List<ListViewItem>();
            foreach (ListViewItem item in listViewQQ.Items)
            {
                if (item.Checked)
                { // 检查是否被勾选
                    checkedItems.Add(item);
                }
            }

            if (checkedItems.Count <= 0)
            {
                MessageBox.Show("请先勾选最左侧QQ列表");
                return;
            }
            // 判断屏蔽功能中的QQ列表是否为空
            List<BlockGroupQQModel> blockGroupQQList = await _blockGroupQQRepository.GetAllAsync();
            if (blockGroupQQList.Count() > 0)
            {
                var result = MessageBox.Show("已有屏蔽任务，删除后无法恢复\n\n\t是否确定删除？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    // 清空屏蔽任务:BlockGroupQQ数据库, 开始新的任务
                    await _blockGroupQQRepository.ClearTableAsync();

                    // 删除屏蔽任务:QQ列表
                    listViewBlockGroupQQ.Items.Clear();

                    LogManager.Info($"[添加屏蔽任务] 清空屏蔽任务:BlockGroupQQ的数据库, 开始新的任务");
                }
                else
                {
                    return;
                }
            }

            await Task.Run(async () =>
            {
                // 默认屏蔽群数为0
                int blockNumber = 0;
                blockGroupQQList = new List<BlockGroupQQModel>();
                foreach (var item in checkedItems)
                {
                    string qq = item.SubItems[1].Text;

                    BlockGroupQQModel blockGroupQQModel = new BlockGroupQQModel();
                    blockGroupQQModel.QQ = qq;
                    blockGroupQQModel.BlockNumber = blockNumber;
                    blockGroupQQModel.CreateTime = DateTime.Now;
                    blockGroupQQModel.UpdateTime = DateTime.Now;
                    // 插入到 block_group_qq 表中
                    await _blockGroupQQRepository.AddOrUpdateAsync(blockGroupQQModel);
                    blockGroupQQList.Add(blockGroupQQModel);
                }
                // 更新UI:ListViewBlockGroupQQ
                UpdateListViewBlockGroupQQ(blockGroupQQList);
                // 更新UI:ListViewBlockGroup
                UpdateListViewBlockGroup();
            });
        }

        private async void btnStartBlockGroup_Click(object sender, EventArgs e)
        {
            if (listViewBlockGroupQQ.Items.Count <= 0)
            {
                MessageBox.Show("任务列表为空, 请先添加任务!");
                return;
            }

            // 确保 textBoxBlockGroupInterval.Text 是一个有效的整数
            if (!int.TryParse(textBoxBlockGroupInterval.Text, out int blockInterval))
            {
                MessageBox.Show("屏蔽间隔必须是一个有效的整数!");
                return;
            }

            // 重置 邀请群状态为进行中的都设置为待处理
            await _blockGroupRepository.ResetStatusToPendingAsync();

            // 更新按钮状态
            UpdateButtonState(btnStartBlockGroup, btnStopBlockGroup, true);

            _blockGroupTaskCancellationTokenSource = new CancellationTokenSource();
            var token = _blockGroupTaskCancellationTokenSource.Token;

            try
            {
                // 开始屏蔽任务
                await Task.Run(async () =>
                {
                    // 重新加载QQ列表(包含群列表)
                    QQList = await _qqService.GetQQList();

                    // 隐藏全部QQ窗口, 防止QQ窗口遮挡
                    ShowOrHideQQMainWindows(Win32Api.SW_HIDE, true);
                    await _blockGroupServices.Start(QQList, blockInterval, token);
                    LogManager.Info("屏蔽任务执行结束");
                    MessageBox.Show("屏蔽任务全部完成!");
                }, token);
            }
            catch (OperationCanceledException)
            {
                MessageBox.Show("屏蔽任务已取消!");
            }
            finally
            {
                // 启用开始按钮，禁用停止按钮
                UpdateButtonState(btnStartBlockGroup, btnStopBlockGroup, false);
            }
        }

        private void btnStopBlockGroup_Click(object sender, EventArgs e)
        {
            if (_blockGroupTaskCancellationTokenSource == null)
            {
                LogManager.Info("暂无屏蔽任务, 无法取消");
                MessageBox.Show("没有正在运行的屏蔽任务");
                return;
            }
            if (_blockGroupTaskCancellationTokenSource.IsCancellationRequested == false)
            {
                LogManager.Info("屏蔽任务已手动取消");
                _blockGroupTaskCancellationTokenSource?.Cancel();
                // 更新按钮状态
                UpdateButtonState(btnStartBlockGroup, btnStopBlockGroup, false);
            }
        }


        /// <summary>
        /// 更新屏蔽任务QQ列表
        /// </summary>
        /// <param name="blockGroupQQModel"></param>
        public async void UpdateListViewBlockGroupQQ(BlockGroupQQModel blockGroupQQModel = null, string qq = null)
        {
            List<BlockGroupQQModel> blockGroupQQModels = new List<BlockGroupQQModel>();
            try
            {
                if (blockGroupQQModel == null)
                {
                    // 从数据库加载屏蔽任务
                    blockGroupQQModels = await _blockGroupQQRepository.GetAllAsync();
                    if (blockGroupQQModels.Count() <= 0)
                    {
                        return;
                    }
                }
                else
                {
                    blockGroupQQModels.Add(blockGroupQQModel);
                }
                if (qq == null)
                {
                    // 默认第一个QQ为进行时
                    qq = blockGroupQQModels.FirstOrDefault()?.QQ;
                }
                UpdateListViewBlockGroupQQ(blockGroupQQModels, qq);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewBlockGroupQQ] UI:更新屏蔽任务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新屏蔽任务QQ列表
        /// </summary>
        /// <param name="blockGroupQQModels"></param>
        /// <param name="qq"></param>
        public void UpdateListViewBlockGroupQQ(List<BlockGroupQQModel> blockGroupQQModels, string qq = null)
        {

            // 自动识别线程, 更新UI
            listViewBlockGroupQQ.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewBlockGroupQQ.BeginUpdate();
                listViewBlockGroupQQ.SuspendLayout(); // 禁用布局更新
                listViewBlockGroupQQ.Items.Clear();

                // 批量添加项
                var itemsToAdd = blockGroupQQModels.Select((blockGroupQQ, index) => CreateListViewBlockGroupQQItem(blockGroupQQ, index + 1, qq)).ToList();
                listViewBlockGroupQQ.Items.AddRange(itemsToAdd.ToArray());

                listViewBlockGroupQQ.ResumeLayout(); // 启用布局更新
                listViewBlockGroupQQ.EndUpdate();
            });
        }

        /// <summary>
        /// 创建一个BlockGroupQQ Item
        /// </summary>
        /// <param name="blockGroupQQ"></param>
        /// <param name="index"></param>
        /// <param name="qq">如果qq不为空则设置为正在进行的状态</param>
        /// <returns></returns>
        private ListViewItem CreateListViewBlockGroupQQItem(BlockGroupQQModel blockGroupQQ, int index, string qq = null)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(blockGroupQQ.QQ);
            newItem.SubItems.Add(blockGroupQQ.BlockNumber.ToString() ?? "0");


            if (qq != null && string.Equals(blockGroupQQ.QQ, qq))
            {
                newItem.BackColor = Color.LightSalmon; // 统一颜色设置
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }

            return newItem;
        }


        /// <summary>
        /// 更新屏蔽任务群列表
        /// </summary>
        /// <param name="qq"></param>
        public async void UpdateListViewBlockGroup(string qq)
        {
            if (string.IsNullOrEmpty(qq))
            {
                LogManager.Error($"[UpdateListViewBlockGroup] UI:更新屏蔽任务失败: qq为空");
                return;
            }
            try
            {
                // 获取该QQ的群列表
                List<BlockGroupModel> blockGroupModels = await _blockGroupRepository.GetByQQAsync(qq);
                if (blockGroupModels == null || blockGroupModels.Count() <= 0)
                {
                    // 数据库没有该QQ的群列表, 重新获取
                    UpdateListViewBlockGroup(qq, null);
                }
                else
                {
                    // 默认该QQ的第一个群号为进行时
                    UpdateListViewBlockGroup(blockGroupModels, blockGroupModels.FirstOrDefault()?.GroupNumber);
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewBlockGroup] UI:更新屏蔽任务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新屏蔽任务群列表
        /// </summary>
        /// <param name="blockGroupQQModel"></param>
        public async void UpdateListViewBlockGroup(BlockGroupModel blockGroupModel)
        {
            if (blockGroupModel == null)
            {
                LogManager.Error($"[UpdateListViewBlockGroup] UI:更新屏蔽任务失败: blockGroupModel为空");
                return;
            }

            try
            {
                List<BlockGroupModel> blockGroupModels = await _blockGroupRepository.GetByQQAsync(blockGroupModel.QQ);
                if (blockGroupModels == null || blockGroupModels.Count() <= 0)
                {
                    LogManager.Error($"[UpdateListViewBlockGroup] UI:更新屏蔽任务失败: qq:{blockGroupModel.QQ}的群为空");
                    return;
                }
                UpdateListViewBlockGroup(blockGroupModels, blockGroupModel.GroupNumber);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewBlockGroup] UI:更新屏蔽任务失败: {ex.Message}");
            }
        }


        /// <summary>
        /// 更新屏蔽任务群列表
        /// </summary>
        /// <param name="qq"></param>
        /// <param name="groupNumber"></param>
        public async void UpdateListViewBlockGroup(string qq = null, string groupNumber = null)
        {
            // 获取对应QQ的群列表
            // QQList = _qqService.GetQQList();
            List<BlockGroupModel> blockGroupModels = new List<BlockGroupModel>();

            // 获取所有屏蔽任务QQ
            List<BlockGroupQQModel> blockGroupQQModels = await _blockGroupQQRepository.GetAllAsync();
            if (blockGroupQQModels.Count() <= 0)
            {
                LogManager.Info($"[UpdateListViewBlockGroup] 暂无屏蔽任务!");
                return;
            }

            List<BlockGroupModel> fristQQGroupList = new List<BlockGroupModel>();

            foreach (var blockGroupQQModel in blockGroupQQModels)
            {

                // 从QQList获取qq对应的 QQ的群列表
                var item = QQList.FirstOrDefault(x => x.QQ == blockGroupQQModel.QQ);
                if (item == null)
                {
                    LogManager.Error($"[UpdateListViewBlockGroup] UI:更新屏蔽任务失败: qq:{blockGroupQQModel.QQ}的群为空");
                    continue;
                }
                // 组装QQ群列表
                List<BlockGroupModel> currentQQGroupList = new List<BlockGroupModel>();
                foreach (var group in item.GroupList)
                {
                    BlockGroupModel blockGroupModel = new BlockGroupModel
                    {
                        QQ = item.QQ,
                        GroupNumber = group,
                        Status = BlockGroupStatus.Pending,  // 默认状态为待处理
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };
                    currentQQGroupList.Add(blockGroupModel);
                    blockGroupModels.Add(blockGroupModel);
                }
            }

            // 批量插入 将群列表存储到数据库
            await _blockGroupRepository.BulkInsertAsync(blockGroupModels);


            if (string.IsNullOrEmpty(qq))
            {
                // 如果qq为空,则取出任务列表第一个QQ
                qq = blockGroupQQModels.FirstOrDefault()?.QQ;
            }

            // 从数据库读取当前QQ的群列表
            List<BlockGroupModel> blockGroupModels1 = await _blockGroupRepository.GetByQQAsync(qq);
            if (blockGroupModels1 == null)
            {
                LogManager.Error($"[UpdateListViewBlockGroup]  qq:{qq} 从数据库读取当前QQ的群列表失败");
                return;
            }

            if (groupNumber == null)
            {
                // 取出 blockGroupModels1 的第一个元素作为groupNumber
                groupNumber = blockGroupModels1.FirstOrDefault().GroupNumber;
            }
            // 更新UI;将当前QQ的群列表展示出来
            UpdateListViewBlockGroup(blockGroupModels1, groupNumber);

        }


        /// <summary>
        /// 更新屏蔽任务群列表
        /// </summary>
        /// <param name="blockGroupModels"></param>
        /// <param name="groupNumber"></param>
        public void UpdateListViewBlockGroup(List<BlockGroupModel> blockGroupModels, string groupNumber = null)
        {

            // 自动识别线程, 更新UI
            listViewBlockGroup.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewBlockGroup.BeginUpdate();
                listViewBlockGroup.SuspendLayout(); // 禁用布局更新
                listViewBlockGroup.Items.Clear();

                if (string.IsNullOrEmpty(groupNumber))
                {
                    // 默认 获取 listViewBlockGroup 第一个的群
                    groupNumber = blockGroupModels.FirstOrDefault().GroupNumber;
                }

                // 批量添加项
                var itemsToAdd = blockGroupModels.Select((blockGroup, index) => CreateListViewBlockGroupItem(blockGroup, index + 1, groupNumber)).ToList();
                listViewBlockGroup.Items.AddRange(itemsToAdd.ToArray());


                // 将列表滚动到 newItem.BackColor = Color.LightSalmon;
                var targetItem = listViewBlockGroup.Items.Cast<ListViewItem>()
                    .FirstOrDefault(x => x.SubItems[1].Text == groupNumber);

                if (targetItem != null)
                {
                    // 直接定位到目标项的下一个项（如果存在）
                    int itemIndex = listViewBlockGroup.Items.IndexOf(targetItem);
                    // 滚动到将item的下一个的item
                    if (itemIndex < listViewBlockGroup.Items.Count - 1)
                    {
                        listViewBlockGroup.Items[itemIndex + 1].EnsureVisible();
                    }
                    else
                    {
                        // 如果是最后一项，直接滚动到自身
                        targetItem.EnsureVisible();
                    }
                }

                listViewBlockGroup.ResumeLayout(); // 启用布局更新
                listViewBlockGroup.EndUpdate();


            });
        }

        /// <summary>
        /// 创建一个 BlockGroup Item
        /// </summary>
        /// <param name="blockGroup"></param>
        /// <param name="index"></param>
        /// <param name="groupNumber">如果groupNumber不为空则设置为正在进行的状态</param>
        /// <returns></returns>
        private ListViewItem CreateListViewBlockGroupItem(BlockGroupModel blockGroup, int index, string groupNumber = null)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(blockGroup.GroupNumber);
            newItem.SubItems.Add(blockGroup.Status.ToChineseString());



            if (blockGroup.Status == BlockGroupStatus.Success)
            {
                newItem.BackColor = Color.LightGreen;
            }
            else if (blockGroup.Status == BlockGroupStatus.Bebeing || string.Equals(blockGroup.GroupNumber, groupNumber))
            {
                newItem.BackColor = Color.LightSalmon;
            }
            else if (blockGroup.Status == BlockGroupStatus.Failed)
            {
                newItem.BackColor = Color.LightCoral;
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }

            return newItem;
        }



        #endregion

        /// =====================================================屏蔽End==================================================
        #region 设置模块
        private async void btnCheckUpdate_Click(object sender, EventArgs e)
        {
            await Task.Run(() => CheckForUpdateEvent());
        }
        private void CheckForUpdateEvent()
        {
            //指定当前版本
            AutoUpdater.InstalledVersion = _version;//当前的App版本
            AutoUpdater.HttpUserAgent = "AutoUpdater";
            AutoUpdater.ReportErrors = true;

            //设置下载后的压缩包存储地址 如果不设置采用默认
            //AutoUpdater.DownloadPath = AppDomain.CurrentDomain.BaseDirectory + @"\AutoUpdater";
            ////设置安装地址 对于zip压缩包 对应的就是解压的地址
            AutoUpdater.InstallationPath = AppDomain.CurrentDomain.BaseDirectory;

            //AutoUpdater.ShowSkipButton = false;//禁用跳过
            //AutoUpdater.ShowRemindLaterButton = false;//禁用稍后提醒

            // 稍后提醒设置
            //AutoUpdater.LetUserSelectRemindLater = false;
            //AutoUpdater.RemindLaterTimeSpan = RemindLaterFormat.Days;
            //AutoUpdater.RemindLaterAt = 2;
            //AutoUpdater.TopMost = true;
            //此处的url为服务器存放的xml文件地址
            AutoUpdater.Start("http://49.235.27.236/update.xml");
        }

        /// <summary>
        /// 定时器事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void timer1_Tick(object sender, EventArgs e)
        {
            if (checkBoxCloseUpdateQQWindow.Checked)
            {
                Win32Api.CloseAllQQWindows("更新提醒");
            }

            if (checkBoxCloseQQGuild.Checked)
            {
                // 判断是否有QQGuild.exe进程，如果有则关闭
                if (Win32Api.IsProcessRunning("QQGuild"))
                {
                    LogManager.Info("QQGuild.exe 进程正在运行，正在关闭...");
                    Win32Api.CloseAllProcess("QQGuild.exe");
                }
            }
            //LogManager.Info($"[定时器] 正在运行");
        }

        #endregion
        #region ListViewAddGroup右键菜单
        private void 导出失败ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 将listViewAddGroup第三列为  AddGroupStatus.Failed.ToChineseString() 的群号导出
            // 创建一个列表来存储失败的群号
            List<string> failedGroupNumbers = new List<string>();

            // 遍历 listViewAddGroup 的所有项
            foreach (ListViewItem item in listViewAddGroup.Items)
            {
                // 获取第三列的值
                string status = item.SubItems[2].Text;

                // 检查第三列的值是否为 AddGroupStatus.Failed.ToChineseString()
                if (status == AddGroupStatus.Failed.ToChineseString())
                {
                    // 获取群号（假设群号在第二列）
                    string groupNumber = item.SubItems[1].Text;
                    failedGroupNumbers.Add(groupNumber);
                }
            }
        }

        private async void 设为未用ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 将鼠标选中的行设置为未用
            if (listViewAddGroup.SelectedItems.Count > 0)
            {
                foreach (ListViewItem item in listViewAddGroup.SelectedItems)
                {
                    string qq = item.SubItems[1].Text;
                    if (string.IsNullOrEmpty(qq)) continue;
                    // 更新数据库
                    await _addGroupRepository.UpdateStatusByGroupNumberAsync(item.SubItems[1].Text, AddGroupStatus.NotStart);
                    item.SubItems[2].Text = AddGroupStatus.NotStart.ToChineseString();
                    // 设置颜色
                    item.BackColor = Color.White;
                }
            }
        }

        private void 删除当前ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 删除鼠标选中的行
            if (listViewAddGroup.SelectedItems.Count > 0)
            {
                foreach (ListViewItem item in listViewAddGroup.SelectedItems)
                {
                    string groupNumber = item.SubItems[1].Text;
                    if (string.IsNullOrEmpty(groupNumber)) continue;
                    // 删除数据库
                    _addGroupRepository.DeleteByGroupNumberAsync(groupNumber);
                    // 删除ListViewAddGroup中的项
                    listViewAddGroup.Items.Remove(item);
                }
            }
        }

        private async void 删除全部ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // 询问用户是否删除
            var result = MessageBox.Show("确定删除全部吗？", "提示", MessageBoxButtons.YesNo);
            if (result == DialogResult.No)
            {
                return;
            }

            // 清表数据表 add_group
            await _addGroupRepository.ClearTableAsync();
            // 删除ListViewAddGroup中的所有项
            listViewAddGroup.Items.Clear();
        }
        #endregion
        #region ListViewInviteGroupQQ右键菜单
        private void 复制全部QQToolStripMenuItem_Click(object sender, EventArgs e)
        {

            // 复制ListViewInviteGroupQQ中的全部QQ到剪贴板
            string clipboardText = "";
            foreach (ListViewItem item in listViewInviteGroupQQ.Items)
            {
                clipboardText += item.SubItems[1].Text + "\r\n";
            }
            if (clipboardText == "")
            {
                MessageBox.Show("没有找到QQ");
                return;
            }
            Clipboard.SetText(clipboardText);
            MessageBox.Show("复制成功");
        }
        #endregion


        #region 群发模块

        /// <summary>
        /// 更新群发任务QQ列表
        /// </summary>
        /// <param name="sendGroupMsgQQModel"></param>
        public async void UpdateListViewSendGroupMsgQQ(SendGroupMsgQQModel sendGroupMsgQQModel = null, string qq = null)
        {
            List<SendGroupMsgQQModel> sendGroupMsgQQModels = new List<SendGroupMsgQQModel>();
            try
            {
                if (sendGroupMsgQQModel == null)
                {
                    // 从数据库加载群发任务
                    sendGroupMsgQQModels = await _sendGroupMsgQQRepository.GetAllAsync();
                    if (sendGroupMsgQQModels.Count() <= 0)
                    {
                        return;
                    }
                }
                else
                {
                    sendGroupMsgQQModels.Add(sendGroupMsgQQModel);
                }
                if (qq == null)
                {
                    // 默认第一个QQ为进行时
                    qq = sendGroupMsgQQModels.FirstOrDefault()?.QQ;
                }
                UpdateListViewSendGroupMsgQQ(sendGroupMsgQQModels, qq);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewSendGroupMsgQQ] UI:更新群发任务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新群发任务QQ列表
        /// </summary>
        /// <param name="sendGroupMsgQQModels"></param>
        /// <param name="qq"></param>
        public void UpdateListViewSendGroupMsgQQ(List<SendGroupMsgQQModel> sendGroupMsgQQModels, string qq = null)
        {

            // 自动识别线程, 更新UI
            listViewSendGroupMsgQQ.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewSendGroupMsgQQ.BeginUpdate();
                listViewSendGroupMsgQQ.SuspendLayout(); // 禁用布局更新
                listViewSendGroupMsgQQ.Items.Clear();

                // 批量添加项
                var itemsToAdd = sendGroupMsgQQModels.Select((sendGroupMsgQQ, index) => CreateListViewSendGroupMsgQQItem(sendGroupMsgQQ, index + 1, qq)).ToList();
                listViewSendGroupMsgQQ.Items.AddRange(itemsToAdd.ToArray());

                listViewSendGroupMsgQQ.ResumeLayout(); // 启用布局更新
                listViewSendGroupMsgQQ.EndUpdate();
            });
        }

        /// <summary>
        /// 创建一个SendGroupMsgQQ Item
        /// </summary>
        /// <param name="sendGroupMsgQQ"></param>
        /// <param name="index"></param>
        /// <param name="qq">如果qq不为空则设置为正在进行的状态</param>
        /// <returns></returns>
        private ListViewItem CreateListViewSendGroupMsgQQItem(SendGroupMsgQQModel sendGroupMsgQQ, int index, string qq = null)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(sendGroupMsgQQ.QQ);
            newItem.SubItems.Add(sendGroupMsgQQ.SendCount.ToString());
            newItem.SubItems.Add(sendGroupMsgQQ.FailedCount.ToString());


            if (qq != null && string.Equals(sendGroupMsgQQ.QQ, qq))
            {
                newItem.BackColor = Color.LightSalmon; // 统一颜色设置
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }

            return newItem;
        }


        /// <summary>
        /// 更新群发任务群列表
        /// </summary>
        /// <param name="qq"></param>
        public async void UpdateListViewSendGroupMsg(string qq)
        {
            if (string.IsNullOrEmpty(qq))
            {
                LogManager.Error($"[UpdateListViewSendGroupMsg] UI:更新群发任务失败: qq为空");
                return;
            }
            try
            {
                // 获取该QQ的群列表
                List<SendGroupMsgModel> sendGroupMsgModels = await _sendGroupMsgRepository.GetByQQAsync(qq);
                if (sendGroupMsgModels == null || sendGroupMsgModels.Count() <= 0)
                {
                    // 数据库没有该QQ的群列表, 重新获取
                    UpdateListViewSendGroupMsg(qq, null);
                }
                else
                {
                    // 默认该QQ的第一个群号为进行时
                    UpdateListViewSendGroupMsg(sendGroupMsgModels, sendGroupMsgModels.FirstOrDefault()?.GroupNumber);
                }
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewSendGroupMsg] UI:更新群发任务失败: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新群发任务群列表
        /// </summary>
        /// <param name="sendGroupMsgQQModel"></param>
        public async void UpdateListViewSendGroupMsg(SendGroupMsgModel sendGroupMsgModel)
        {
            if (sendGroupMsgModel == null)
            {
                LogManager.Error($"[UpdateListViewSendGroupMsg] UI:更新群发任务失败: sendGroupMsgModel为空");
                return;
            }

            try
            {
                List<SendGroupMsgModel> sendGroupMsgModels = await _sendGroupMsgRepository.GetByQQAsync(sendGroupMsgModel.QQ);
                if (sendGroupMsgModels == null || sendGroupMsgModels.Count() <= 0)
                {
                    LogManager.Error($"[UpdateListViewSendGroupMsg] UI:更新群发任务失败: qq:{sendGroupMsgModel.QQ}的群为空");
                    return;
                }
                UpdateListViewSendGroupMsg(sendGroupMsgModels, sendGroupMsgModel.GroupNumber);
            }
            catch (Exception ex)
            {
                // 记录异常日志
                LogManager.Error($"[UpdateListViewSendGroupMsg] UI:更新群发任务失败: {ex.Message}");
            }
        }


        /// <summary>
        /// 更新群发任务群列表
        /// </summary>
        /// <param name="qq"></param>
        /// <param name="groupNumber"></param>
        public async void UpdateListViewSendGroupMsg(string qq = null, string groupNumber = null)
        {
            // 获取对应QQ的群列表
            // QQList = _qqService.GetQQList();
            List<SendGroupMsgModel> sendGroupMsgModels = new List<SendGroupMsgModel>();

            // 获取所有群发任务QQ
            List<SendGroupMsgQQModel> sendGroupMsgQQModels = await _sendGroupMsgQQRepository.GetAllAsync();
            if (sendGroupMsgQQModels.Count() <= 0)
            {
                LogManager.Info($"[UpdateListViewSendGroupMsg] 暂无群发任务!");
                return;
            }
            // 默认发送图片
            SendGroupMsgType msgType = SendGroupMsgType.图片;
            // 获取当前发送的资源类型
            comboBoxSendType.InvokeIfRequired(() =>
            {
                if (comboBoxSendType.SelectedIndex == -1)
                {
                    msgType = SendGroupMsgType.图片;
                }
                else
                {
                    msgType = (SendGroupMsgType)comboBoxSendType.SelectedIndex;
                }
            });


            List<SendGroupMsgModel> fristQQGroupList = new List<SendGroupMsgModel>();

            foreach (var sendGroupMsgQQModel in sendGroupMsgQQModels)
            {

                // 从QQList获取qq对应的 QQ的群列表
                var item = QQList.FirstOrDefault(x => x.QQ == sendGroupMsgQQModel.QQ);
                if (item == null)
                {
                    LogManager.Error($"[UpdateListViewSendGroupMsg] UI:更新群发任务失败: qq:{sendGroupMsgQQModel.QQ}的群为空");
                    continue;
                }
                // 组装QQ群列表
                List<SendGroupMsgModel> currentQQGroupList = new List<SendGroupMsgModel>();
                foreach (var group in item.GroupList)
                {
                    SendGroupMsgModel sendGroupMsgModel = new SendGroupMsgModel
                    {
                        QQ = item.QQ,
                        GroupNumber = group,
                        MessageContent = "1",                   // 发送图片的下标
                        MessageType = msgType,
                        Status = SendGroupMsgStatus.NotStarted, // 默认:未开始
                        SendTime = DateTime.Now,
                        RetryCount = 3,                         // 默认重试3次
                        SendCount = 0,                          // 默认发送次数0
                        CreateTime = DateTime.Now,
                        UpdateTime = DateTime.Now
                    };
                    currentQQGroupList.Add(sendGroupMsgModel);
                    sendGroupMsgModels.Add(sendGroupMsgModel);
                }
            }

            // 批量插入 将群列表存储到数据库
            await _sendGroupMsgRepository.BulkInsertAsync(sendGroupMsgModels);


            if (string.IsNullOrEmpty(qq))
            {
                // 如果qq为空,则取出任务列表第一个QQ
                qq = sendGroupMsgQQModels.FirstOrDefault()?.QQ;
            }

            // 从数据库读取当前QQ的群列表
            List<SendGroupMsgModel> sendGroupMsgModels1 = await _sendGroupMsgRepository.GetByQQAsync(qq);
            if (sendGroupMsgModels1 == null)
            {
                LogManager.Error($"[UpdateListViewSendGroupMsg]  qq:{qq} 从数据库读取当前QQ的群列表失败");
                return;
            }

            if (groupNumber == null)
            {
                // 取出 send
                // GroupMsgModels1 的第一个元素作为groupNumber
                groupNumber = sendGroupMsgModels1.FirstOrDefault().GroupNumber;
            }
            // 更新UI;将当前QQ的群列表展示出来
            UpdateListViewSendGroupMsg(sendGroupMsgModels1, groupNumber);

        }


        /// <summary>
        /// 更新群发任务群列表
        /// </summary>
        /// <param name="sendGroupMsgModels"></param>
        /// <param name="groupNumber"></param>
        public void UpdateListViewSendGroupMsg(List<SendGroupMsgModel> sendGroupMsgModels, string groupNumber = null)
        {

            // 自动识别线程, 更新UI
            listViewSendGroupMsg.InvokeIfRequired(() =>
            {
                // 使用 BeginUpdate 和 EndUpdate 减少闪烁
                listViewSendGroupMsg.BeginUpdate();
                listViewSendGroupMsg.SuspendLayout(); // 禁用布局更新
                listViewSendGroupMsg.Items.Clear();

                if (string.IsNullOrEmpty(groupNumber))
                {
                    // 默认 获取 listViewSendGroupMsg 第一个的群
                    groupNumber = sendGroupMsgModels.FirstOrDefault().GroupNumber;
                }

                // 批量添加项
                var itemsToAdd = sendGroupMsgModels.Select((sendGroupMsg, index) => CreateListViewSendGroupMsgItem(sendGroupMsg, index + 1, groupNumber)).ToList();
                listViewSendGroupMsg.Items.AddRange(itemsToAdd.ToArray());


                // 将列表滚动到 newItem.BackColor = Color.LightSalmon;
                var targetItem = listViewSendGroupMsg.Items.Cast<ListViewItem>()
                    .FirstOrDefault(x => x.SubItems[1].Text == groupNumber);

                if (targetItem != null)
                {
                    // 直接定位到目标项的下一个项（如果存在）
                    int itemIndex = listViewSendGroupMsg.Items.IndexOf(targetItem);
                    // 滚动到将item的下一个的item
                    if (itemIndex < listViewSendGroupMsg.Items.Count - 1)
                    {
                        listViewSendGroupMsg.Items[itemIndex + 1].EnsureVisible();
                    }
                    else
                    {
                        // 如果是最后一项，直接滚动到自身
                        targetItem.EnsureVisible();
                    }
                }

                listViewSendGroupMsg.ResumeLayout(); // 启用布局更新
                listViewSendGroupMsg.EndUpdate();


            });
        }

        /// <summary>
        /// 创建一个 SendGroupMsg Item
        /// </summary>
        /// <param name="sendGroupMsg"></param>
        /// <param name="index"></param>
        /// <param name="groupNumber">如果groupNumber不为空则设置为正在进行的状态</param>
        /// <returns></returns>
        private ListViewItem CreateListViewSendGroupMsgItem(SendGroupMsgModel sendGroupMsg, int index, string groupNumber = null)
        {
            ListViewItem newItem = new ListViewItem(index.ToString());
            newItem.SubItems.Add(sendGroupMsg.GroupNumber);
            newItem.SubItems.Add(sendGroupMsg.MessageType.ToString());
            newItem.SubItems.Add($"{sendGroupMsg.SendCount}/{sendGroupMsg.RetryCount}");
            newItem.SubItems.Add(sendGroupMsg.Status.ToChineseString());

            //if (groupNumber != null && string.Equals(sendGroupMsg.GroupNumber, groupNumber))
            //{
            //    newItem.BackColor = Color.LightSalmon; // 统一颜色设置
            //    newItem.EnsureVisible();// 使滚动条自动滚动到该行‌
            //}
            //else
            //{
            //    newItem.BackColor = Color.Transparent;
            //}
            if (sendGroupMsg.Status == SendGroupMsgStatus.Success)
            {
                newItem.BackColor = Color.LightGreen;
            }
            else if (sendGroupMsg.Status == SendGroupMsgStatus.Running || string.Equals(sendGroupMsg.GroupNumber, groupNumber))
            {
                newItem.BackColor = Color.LightSalmon;
            }
            else if (sendGroupMsg.Status == SendGroupMsgStatus.Failed)
            {
                newItem.BackColor = Color.LightCoral;
            }
            else
            {
                newItem.BackColor = Color.Transparent;
            }


            return newItem;
        }


        private async void btnAddSendGroupMsgTask_Click(object sender, EventArgs e)
        {
            // 刷新添加QQ列表
            // 处理 addGroupsQQ 列表
            // 判断 listViewQQ 的选中相
            // 获取所有勾选的 ListViewItem
            List<ListViewItem> checkedItems = new List<ListViewItem>();
            foreach (ListViewItem item in listViewQQ.Items)
            {
                if (item.Checked)
                { // 检查是否被勾选
                    checkedItems.Add(item);
                }
            }

            if (checkedItems.Count <= 0)
            {
                MessageBox.Show("请先勾选最左侧QQ列表");
                return;
            }
            // 判断邀请功能中的QQ列表是否为空
            List<SendGroupMsgQQModel> sendGroupMsgQQModels = await _sendGroupMsgQQRepository.GetAllAsync();
            if (sendGroupMsgQQModels.Count() > 0)
            {
                var result = MessageBox.Show("已有群发任务，删除后无法恢复\n\n\t是否确定删除？", "提示", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    // UI:删除群发任务:QQ列表
                    listViewSendGroupMsgQQ.Items.Clear();
                    // 数据库:清空群发任务:send_group_msg_qq
                    await _sendGroupMsgQQRepository.ClearTableAsync();


                    // UI:删除群发任务:群列表
                    listViewSendGroupMsg.Items.Clear();
                    // 数据库:清空群发任务:send_group_msg
                    await _sendGroupMsgRepository.ClearTableAsync();

                    // 删除记录qq
                    // SaveAddGroudProgress("");

                    LogManager.Info($"[添群发发任务] 清空群发任务:send_group_msg_qq和send_group_msg的数据库, 开始新的任务");
                }
                else
                {
                    return;
                }
            }

            await Task.Run(async () =>
            {
                string firstQQ = null;
                sendGroupMsgQQModels = new List<SendGroupMsgQQModel>();
                for (int i = 0; i < checkedItems.Count; i++)
                {
                    ListViewItem item = checkedItems[i];

                    string qq = item.SubItems[1].Text;

                    // 插入到 send_group_msg_qq 表中
                    SendGroupMsgQQModel sendGroupMsgQQModel = new SendGroupMsgQQModel();

                    sendGroupMsgQQModel.QQ = qq;
                    sendGroupMsgQQModel.SendCount = 0;
                    sendGroupMsgQQModel.FailedCount = 0;
                    sendGroupMsgQQModel.ResourceIndex = 1; // 默认资源下标为1
                    sendGroupMsgQQModel.CreateTime = DateTime.Now;
                    sendGroupMsgQQModel.UpdateTime = DateTime.Now;

                    await _sendGroupMsgQQRepository.AddOrUpdateAsync(sendGroupMsgQQModel);
                    if (i == 0)
                    {
                        // 将第一个QQ设置为正在进行的状态
                        firstQQ = qq;
                    }
                    sendGroupMsgQQModels.Add(sendGroupMsgQQModel);
                }
                // 更新UI:ListViewSendGroupMsgQQ, 将第一个QQ设置为正在进行的状态
                UpdateListViewSendGroupMsgQQ(sendGroupMsgQQModels, firstQQ);
                // 更新UI:ListViewSendGroupMsg, 将第一个QQ群号设置为正在进行的状态
                UpdateListViewSendGroupMsg(qq: firstQQ);
            });
        }

        private async void btnStartSendGroupMsg_Click(object sender, EventArgs e)
        {
            if (listViewSendGroupMsgQQ.Items.Count <= 0)
            {
                MessageBox.Show("任务列表为空, 请先添加任务!");
                return;
            }

            // 确保 tbSendInterval1.Text 是一个有效的整数
            if (!int.TryParse(tbSendIntervalStart.Text, out int sendIntervalStart) || sendIntervalStart <= 0)
            {
                MessageBox.Show("间隔时间开始值必须是一个有效的正整数!");
                return;
            }

            if (!int.TryParse(tbSendIntervalEnd.Text, out int sendIntervalEnd) || sendIntervalEnd <= 0 || sendIntervalEnd < sendIntervalStart)
            {
                MessageBox.Show("间隔时间结束值必须是一个有效的正整数且大于等于开始值!");
                return;
            }


            // 确保 tbBatchRecipientCount.Text 是一个有效的整数
            if (!int.TryParse(tbBatchSendCount.Text, out int batchRecipientCount) || batchRecipientCount <= 0)
            {
                MessageBox.Show("单次群发数量必须是一个有效的正整数!");
                return;
            }

            // 确保 tbAccountTotalSend.Text 是一个有效的整数
            if (!int.TryParse(tbAccountTotalSend.Text, out int accountTotalSend) || accountTotalSend <= 0)
            {
                MessageBox.Show("单号群发数量必须是一个有效的正整数!");
                return;
            }

            if (comboBoxSendType.SelectedIndex < 0)
            {
                MessageBox.Show("请选择群发类型!");
                return;
            }
            // 群发类型 获取 comboBoxSendType 的值
            SendGroupMsgType msgType = (SendGroupMsgType)comboBoxSendType.SelectedIndex;
            string picPath = tbSendGroupMsgPicPath.Text ?? string.Empty;
            if (msgType == SendGroupMsgType.图片 && string.IsNullOrEmpty(picPath))
            {
                MessageBox.Show("请选择图片路径!");
                return;
            }

            // 重置 群发状态为进行中的都设置为待处理
            await _sendGroupMsgRepository.ResetStatusRunningToNotStartedAsync();

            // 更新按钮状态
            UpdateButtonState(btnStartSendGroupMsg, btnStopSendGroupMsg, true);

            _sendGroupMsgTaskCancellationTokenSource = new CancellationTokenSource();
            var token = _sendGroupMsgTaskCancellationTokenSource.Token;

            try
            {
                // 开始邀请
                await Task.Run(async () =>
                {
                    // 重新加载QQ列表(包含群列表)
                    QQList = await _qqService.GetQQList();

                    await _sendGroupMsgServices.Start(QQList, msgType, picPath, sendIntervalStart, sendIntervalEnd, batchRecipientCount, accountTotalSend, token);
                    MessageBox.Show("群发任务全部完成!");
                }, token);
                // await _inviteAddGroup.Start(textBoxInviteList.Text, inviteInterval);
            }
            catch (OperationCanceledException)
            {
                MessageBox.Show("群发任务已取消!");
            }
            finally
            {
                // 启用开始按钮，禁用停止按钮
                UpdateButtonState(btnStartSendGroupMsg, btnStopSendGroupMsg, false);
            }
        }


        private void btnStopSendGroupMsg_Click(object sender, EventArgs e)
        {
            if (_sendGroupMsgTaskCancellationTokenSource == null)
            {
                LogManager.Info("暂无群发任务, 无法取消");
                MessageBox.Show("没有正在运行的群发任务");
                return;
            }
            if (_sendGroupMsgTaskCancellationTokenSource.IsCancellationRequested == false)
            {
                LogManager.Info("群发任务已手动取消");
                _sendGroupMsgTaskCancellationTokenSource?.Cancel();
                // 更新按钮状态
                UpdateButtonState(btnStartSendGroupMsg, btnStopSendGroupMsg, false);
            }
        }
        private async void toolStripMenuItem6_Click(object sender, EventArgs e)
        {

            await _sendGroupMsgRepository.UpdateFaildToNotStart();
            List<SendGroupMsgModel> sendGroupMsgModels = await _sendGroupMsgRepository.GetAllAsync();
            // 重新加载表格
            UpdateListViewSendGroupMsg(sendGroupMsgModels);
        }
        private void tbSendGroupMsgPicPath_TextChanged(object sender, EventArgs e)
        {
            // 保存控件内容
            SaveControlsContents();
            //// 获取拖放的文件路径数组
            //string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);

            //// 过滤非目录项（仅保留文件夹路径）
            //var directories = files.Where(f => Directory.Exists(f));

            //// 如果有有效目录，显示第一个目录路径
            //if (directories.Any())
            //{
            //    tbSendGroupMsgPicPath.Text = directories.First();
            //    // 保存控件内容
            //    SaveControlsContents();
            //}
            //else
            //{
            //    MessageBox.Show("请拖动有效的文件夹路径");
            //}
        }


        #endregion



    }
}
